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
- What mistake am I making?
- 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
The regex used with
NSPRedicateandMATCHESmust match the whole string, so you need to useOr - if there can be mutliple lines in the input string:
to let the
.*consume the rest of the string.If the string must end with
Test, useYou do not even need the
^or$anchors here since they are implicit here.If the string must contain a
Testsubstring, useNote that this is not efficient though due to high backtracking caused by the first
.*.