Objective-C/Swift regex matching across multliple lines

I have a regular expression originally used in python to extract 2 strings from a scraped HTML page : var\s+kaynaklar.*?url\s*:\s*\"([^\"]+)\"\s*,\s*data\s*:\s*'([^']+)

This works fine in Python but not in Objective-C/Swift.

  • Swift Generics: More specialized than generic?
  • Parsing CSV file in Swift
  • Is there a number type with bigger capacity than u_long/UInt64 in Swift?
  • delete row UITableView index issue
  • Class are being linked more than once in target
  • Force refresh on another ViewController component with swift
  • This is the Swift 2.0 code I’m using to find the results:

    do {
            let regexString = "var\\s+kaynaklar.*?url\\s*:\\s*\\\"([^\\\"]+)\\\"\\s*,\\s*data\\s*:\\s*'([^']+)"
            let regex = try NSRegularExpression(pattern: regexString, options: [])
            let nsString = text as NSString
            let results = regex.matchesInString(text,
                options: [], range: NSMakeRange(0, nsString.length))
            return results.map { nsString.substringWithRange($0.range)}
        } catch let error as NSError {
            print("invalid regex: \(error.localizedDescription)")
            return []

    And this is an example of the JS being checked inside the HTML looks like :

    var kaynaklar = [];
                jQuery("#player").html("<br><br><font style='color:white;'>Video kaynağı silinmiş lütfen sol üstten Kaynak butonuna tıklayarak farklı bir kaynak deneyin.</font>")
                for (var i = 1; i < 6; i++) {
                        kaynaklar.push({"file":a["videolink"+i], "label":a["videokalite"+i],"type":"mp4"});
            jQuery("#player").html("<br><br><font style='color:white;'>Video yüklenirken bir hata oluştu lütfen sayfayı yenileyip tekrar deneyin veya farklı bir kaynak deneyin.</font>")

    Solutions Collect From Internet About “Objective-C/Swift regex matching across multliple lines”

    From your feedback, I see you just need to tell the regex engine to match a newline with a period.

    Use the NSRegularExpressionOptions.DotMatchesLineSeparators option:

    Allow . to match any character, including line separators.

    Available in OS X v10.7 and later.

    As a quicker-to-implement alternative, use an inline (?s) modifier at the beginning of the pattern:

    let regexString = "(?s)var\\s+kaynaklar.*?url\\s*:\\s*\\\"([^\\\"]+)\\\"\\s*,\\s*data\\s*:\\s*'([^']+)"

    See the regex demo.