Use Regex with NSPredicate

263 Views Asked by At

Aim

  • Using NSPredicate I would like to use Regex to match all strings beginning with "Test"
  • I specifically want to use Regex and NSPredicate.

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", "[email protected]", "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
[email protected] - false
Test - true
Test 123 - false
2

There are 2 best solutions below

4
Wiktor Stribiżew On BEST ANSWER

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 .*.

2
Wolfgang Wilke On

You try an exact match.... try with MATCHES, try LIKE or CONTAINS instead.

let predicate = NSPredicate(format: "SELF CONTAINS %@", pattern)

See Here as you need