0

I am trying to use NSRegularExpression(pattern: regex) to extract 10.32.15.235 in a string: \"IPAddress\":\"10.32.15.235\",\"WAN\" using Swift 3.

However, I'm getting an error using this function from this answer

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

With this call:

        let pattern = "IPAddress\\\":\\\"(.+?)\\"
        let IPAddressString = self.matches(for: pattern, in: stringData!)
        print(IPAddressString)

However, the error part of the function is called with this error:

invalid regex: The value “IPAddress\":\"(.+?)\” is invalid.

Can you help me modify the regex expression for Swift 3?

Thanks

Jazzmine
  • 1,837
  • 8
  • 36
  • 54

1 Answers1

0

Note that in case you have a valid JSON, you may use a JSON parser with Swift.

TO fix your current regex approach, you may use

let pattern = "(?<=IPAddress\":\")[^\"]+"

Pattern details

  • (?<=IPAddress\":\") - a positive lookahead that matches a position in the string right after IPAddress":" substring
  • [^\"]+ - a negated character class matching 1 or more chars other than "

See the regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563