Aim
- Using
NSPredicate
I would like to use Regex to match all strings beginning with "Test" - I specifically want to use
Regex
andNSPredicate
.
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
2
Answers
The regex used with
NSPRedicate
andMATCHES
must 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
Test
substring, useNote that this is not efficient though due to high backtracking caused by the first
.*
.You try an exact match…. try with MATCHES, try LIKE or CONTAINS instead.
See Here as you need