I'm trying to build a regex to match a specific format. The regex is this :
let regex = NSRegularExpression.init(#"[A-Z]{2}: (\d*(.?\d{1,2})?)\\|$"#)
I wrote it using regexr.com, using this format : [A-Z]{2}\:\s(\d*(\.?\d{1,2})?)\|$
.
I show you how it should work :
"AL: 90|" fine
"AL: 8.2|" fine
"AL" wrong
"AL: 8" wrong
Hope I gave you the idea.
Now, here's the extension I'm using.
extension NSRegularExpression {
convenience init(_ pattern: String) {
do {
try self.init(pattern: pattern)
} catch {
preconditionFailure("Illegal regular expression: \(pattern).")
}
}
}
// MARK: - Matches
extension NSRegularExpression {
func matches(_ string: String) -> Bool {
let range = NSRange(location: 0, length: string.utf16.count)
return firstMatch(in: string, options: [], range: range) != nil
}
}
This is the code :
let regex = NSRegularExpression.init(#"[A-Z]{2}: (\d*(.?\d{1,2})?)\\|$"#)
if regex.matches(message.text) {
print("Matches!")
} else {
print("Text not valid!")
}
And it's not working. It gives me these results :
"al" matches
"aAl" matches
"AL: 9" matches
I really cannot understand what's wrong with my regex as on regexr works fine.