Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift regular expression format?

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?

like image 807
MLyck Avatar asked Mar 07 '15 17:03

MLyck


People also ask

What is regular expression in Swift?

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.

What is Regex in iOS?

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.

How do I validate an email in swift 5?

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.

WHAT IS A in Regex?

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".


2 Answers

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})?$" 
like image 124
Avinash Raj Avatar answered Oct 19 '22 22:10

Avinash Raj


Edit (June 2022)

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 #"..."#:

  • Your regex pattern is parsed at the compile-time, so you don't need to worry if your pattern is valid or not once your program is compiled
  • If your pattern is invalid, the compiler lets you know specifically which part is invalid as the compile error
  • Syntax highlighting is applied

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
    }
}

Original answer

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})?$"#
like image 5
Manabu Avatar answered Oct 19 '22 21:10

Manabu