iosswiftregexnspredicate

Use Regex with NSPredicate


Aim

Questions

  1. What mistake am I making?
  2. What is the right way to use Regex to achieve what I am trying to do.

Code (My attempt, doesn't work)

let tests = ["Testhello", "Car", "a@b.com", "Test", "Test 123"]
let pattern = "^Test"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)

for test in tests {
    let eval = predicate.evaluate(with: test)
    print("\(test) - \(eval)")
}

Output

Testhello - false
Car - false
a@b.com - false
Test - true
Test 123 - false

Solution

  • The regex used with NSPRedicate and MATCHES must match the whole string, so you need to use

    let pattern = "Test.*"
    

    Or - if there can be mutliple lines in the input string:

    let pattern = "(?s)Test.*"
    

    to let the .* consume the rest of the string.

    If the string must end with Test, use

    let pattern = "(?s).*Test"
    

    You do not even need the ^ or $ anchors here since they are implicit here.

    If the string must contain a Test substring, use

    let pattern = "(?s).*Test.*"
    

    Note that this is not efficient though due to high backtracking caused by the first .*.