user3695826 user3695826 - 4 months ago 28
iOS Question

swift Regular Expression and (.*?)

I want to extract substrings from a string that match a regex pattern.

The problem is this code :

("ytplayer.config = {(.*?)};").exec(responseStringC)
. It must match but return nil.

string.exec function :

extension String {
func exec (str: String) -> Array<String> {
do {
let regex = try NSRegularExpression(pattern: self, options: [.CaseInsensitive,.IgnoreMetacharacters])
let nsstr = str as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches : Array<String> = Array<String>()
regex.enumerateMatchesInString(str, options: NSMatchingOptions(rawValue: 0), range: all) {
(result : NSTextCheckingResult?, _, _) in
let theResult = nsstr.substringWithRange(result!.range)
matches.append(theResult)
}
return matches
} catch {
print("error")
return Array<String>()
}
}
}


"responseStringC" variable is :

http://pastebin.com/uvvq9ULA

the problem is return nil. Any Clue?

Answer

Your exec code contains .IgnoreMetacharacters flag:

Treat the entire pattern as a literal string.

Remove it so that the pattern could be treated as a regex pattern.

Also, a good idea is to use a DOTALL modifier (?s) at the start of the pattern.

Also, remember that a dot matches any character, escape it to match a literal dot.

As for the pattern, I'd recommend

"(?s)ytplayer\\.config = {(.*?)};"

Or a much faster:

"(?s)ytplayer\\.config = {([^}]*(?:\\}(?!;)[^}]*)*)\\};"

See the regex demo