NSPredicate
I would like to use Regex to match all strings beginning with "Test"Regex
and NSPredicate
.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)")
}
Testhello - false
Car - false
a@b.com - false
Test - true
Test 123 - false
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 .*
.