swiftregextextfieldcity

City Name validation Regex Swift 4


I have been trying to implement a regex validation for a given city name.

My regex should match cities names like:

NY
San Francisco
München
København
Saint-Tropez
St. Lucia

So far I've searched the web for such-like regex but I've been having a hard time trying to implement it in swift.

this is the regex I've come up with, it seems to work in other languages but not in swift:

^[a-zA-Z\\u0080-\\u024F\\s\\/\\-\\)\(\`\.\"\']+$

Also as additional info, I'd like to implement it in the UITextField delegate method:

shouldChangeCharactersIn

something like this:

override func textField(_ textField: UITextField,
                            shouldChangeCharactersIn range: NSRange,
                            replacementString string: String) -> Bool {

        return validNameRegex.matches(string)
    }

using a NSRegularExpression Extension:

extension NSRegularExpression {

    convenience init(_ pattern: String) {
        do {
            try self.init(pattern: pattern)
        } catch {
            preconditionFailure("Illegal regular expression: \(pattern).")
        }
    }


    func matches(_ string: String) -> Bool {
        let range = NSRange(location: 0, length: string.utf16.count)
        return firstMatch(in: string, options: [], range: range) != nil
    }
}

Hope someone can help me out. Thanks in advance, and happy new year :)


Solution

  • In the end I ended up using this regex:

    ^[a-zA-Z\u{0080}-\u{024F}\\s\\/\\-\\)\\(\\`\\.\\\"\\']*$
    

    the main problem was scaping the "\" characters and the { } in the unicode