I was using a function to validate email format and password up till now
func isRegexValid(string:String,regex:String) -> Bool {
return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: string)
}
I was trying to check a certain pattern and ran into problems. I was looking to find a string with 4 comma delimiters followed by "ext"
^(.*,){4}ext
The above function would not handle this as expected, so I tried an alternative which works well
func isRegexValid2(string:String,pattern:String) -> Bool {
let regex = try! NSRegularExpression(pattern: pattern, options: [])
return regex.firstMatch(in: string, options: [], range: NSMakeRange(0, string.utf16.count)) != nil
}
I would like to understand the differences between the two regex calls and whether we should avoid one or the other.
NSPredicate is very different from NSRegularExpression.
NSPredicate is used for searching and filtering among the Cocoa object. Its primary purpose is to filter certain object among a collection of objects. It has a completely different syntax.
As mentioned in the Apple docs for NSPredicate
Predicates represent logical conditions, which you can use to filter collections of objects.
For further study you can see Predicate programming guide.
On the other hand NSRegularExpression is a class that is used to compile regular expressions that are then applied to unicode strings.
NSRegularExpression class supports standard ICU regular expression defined at http://userguide.icu-project.org/strings/regexp
Hope this clarifies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With