I'm familiar with doing pcre regexes, however they don't seem to work in swift.
^([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$
to validate numbers like 1,000,000.00
However, putting this in my swift function, causes an error.
extension String {
func isValidNumber() -> Bool {
let regex = NSRegularExpression(pattern: "^([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$", options: .CaseInsensitive, error: nil)
return regex?.firstMatchInString(self, options: nil, range: NSMakeRange(0, countElements(self))) != nil
}
}
"Invalid escape sequence in litteral"
This is of course, because pcre uses the "\" character, which swift interprets as an escape (I believe?)
So since I can't just use the regexes I'm used to. How do I translate them to be compatible with Swift code?
Apple provides support for regular expressions on all of its platforms – iOS, macOS, tvOS, and even watchOS – all using the same class, NSRegularExpression . It's an extremely fast and efficient way to search and replace complex text tens of thousands of times, and it's all available for Swift developers to use.
A regex ( also known as regular expressions) is a pattern string. These pattern strings allow you to search specific patterns in documents and to validate email, phone number etc. In iOS and MacOS regex been handled by NSRegularExpression . To know more about NSRegularExpression read apple documentation.
Three Methods to Validate Email in SwiftUsing functions of Swift NSPredicate class to match an email address input with a regular expression. Creating a custom class conforming to RawRepresentable which initializes only if a valid email address is provided.
The power of regular expressions comes from its use of metacharacters, which are special characters (or sequences of characters) used to represent something else. For instance, in a regular expression the metacharacter ^ means "not". So, while "a" means "match lowercase a", "^a" means "do not match lowercase a".
Within double quotes, a single backslash would be readed as an escape sequence. You need to escape all the backslashes one more time in-order to consider it as a regex backslash character.
"^([1-9]\\d{0,2}(,\\d{3})*|([1-9]\\d*))(\\.\\d{2})?$"
From Swift 5.7, which you can use it on Xcode 14.0 Beta 1 or later, you can use /.../
, like this:
// Regex type
let regex = /^([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$/
Advantages over #"..."#
:
So your code would look like this:
extension String {
func isValidNumber() -> Bool {
let regex = /^([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$/
.ignoresCase()
return (try? regex.firstMatch(in: self)) != nil
}
}
Since Swift 5, you can use #"..."#
like this, so that you don't need to add extra escape sequences for Swift:
#"^([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$"#
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