AVR
AVR

Reputation: 139

Regex not working in swift. Giving an error "invalid regex"

I am trying to get substrings from one string. And for that I am applying regex {[^{]*} But its not working in my swift code and giving me an error "invalid regex". Same regex is working with https://regex101.com/r/B8Gwa7/1. I am using following code to apply regex. I need to get substrings between "{" and "}". Can I get same result without using regex or is there anything wrong with my regex or code?.

static func matches(regex: String, text: String) -> Bool {
        do {
            let regex = try NSRegularExpression(pattern: regex, options: [.caseInsensitive])
            let nsString = text as NSString
            let match = regex.firstMatch(in: text, options: [],
                                         range: NSRange(location: .zero, length: nsString.length))
            return match != nil
        } catch {
            print("invalid regex: \(error.localizedDescription)")
            return false
        }
    }

Upvotes: 0

Views: 1202

Answers (1)

vadian
vadian

Reputation: 285059

Curly braces are special characters which have to be escaped

\{[^}]*\}, in a Swift literal string \\{[^}]*\\}

By the way don't use the literal initializer of NSRange to get the length of the string, the highly recommended way is

static func matches(regex: String, text: String) -> Bool {
    do {
        let regex = try NSRegularExpression(pattern: regex, options: .caseInsensitive)
        let match = regex.firstMatch(in: text, options: [],
                                     range: NSRange(text.startIndex..., in: text)
        return match != nil
    } catch {
        print("invalid regex: \(error.localizedDescription)")
        return false
    }
}

Upvotes: 2

Related Questions