0

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
        }
    }
3
  • First of all, you want such regex {[^}]*} Secondly, try escaping characters such as { and } Commented Mar 12, 2021 at 7:59
  • @MichałTurczyn tried using {[^}]*} but still getting same error. Commented Mar 12, 2021 at 8:01
  • Escape it. E.g. #"\{.*?\}"# or #"\{[^}]*\}"#. Commented Mar 12, 2021 at 8:11

1 Answer 1

2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.