skip to Main Content

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

Answers


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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search