I'm trying to check for the following considerations in a number of 4 digits, for a PIN number
- No 4 consecutive digits (1234, 2345, etc), upwards or downwards
- Shouldn't start with
19
or20
to prevent using a year - Have no more than 2 repeated numbers (1112 wrong, 1122 ok)
I have the equivalent regex made for Android:
"^(?!(.)\\1{3})(?!19|20)(?!0123|1234|2345|3456|4567|5678|6789|7890|0987|9876|8765|7654|6543|5432|4321|3210)\\d{4}\$"
But when I use the same pattern in Swift I get:
Invalid escape sequence in literal
Showing a red mark (underline) below the \
on \$
at the very end.
Removing the \
doesn't work as it matches anything
But I'm also not sure that the exact same pattern can be used for Swift, as I've seen other examples with the same error, but for different reason, there I see they don't use double \\
.
For example: Invalid escape sequence in literal with regex
I also created this extension for NSRegularExpression
, that I got from Hacking with Swift so that testing was easier.
extension NSRegularExpression {
func matches(_ string: String) -> Bool {
let range = NSRange(location: 0, length: string.utf16.count)
return firstMatch(in: string, options: [], range: range) != nil
}
}
And this is how my method looks like:
func isValidPIN(_ pin: String) -> Bool {
let pattern = #"""
^(?!(.)\1{3})
(?!19|20)
(?!0123|1234|2345|3456|4567|5678|6789|7890|0987|9876|8765|7654|6543|5432|4321|3210)
\d{4}\z
"""#
let regex = try! NSRegularExpression(pattern: pattern)
return regex.matches(pin)
}
Replacing \$
for \\z
as suggested in the comments helped removing the error, but it's only matching for consecutive numbers, and using custom delimiters shows these results
- 1234 => Not matching - Should match (4 consecutive numbers)
- 1912 => Not matching - Should match (Starts with 19)
- 1112 => Not matching - Should match (3 repeated numbers)
- 7845 => Not matching - Should not match (Valid pin)