Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use Regex with NSPredicate

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", "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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading