user3695826 user3695826 - 1 year ago 134
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)
return matches
} catch {
return Array<String>()

"responseStringC" variable is :

the problem is return nil. Any Clue?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download