Convert JavaScript Regex to Swift Regex

I am learning Swift and I am trying to convert a little JavaScript code to Swift. JavaScript code uses Regex to split the string, as shown below:

var text = "blah.clah##something_else";
var parts = text.match(/(^.*?)\#\#(.+$)/);

after execution, the array partswill contain the following:

["blah.clah##something_else", "blah.clah", "something_else"]

I would like to reproduce the same behavior in Swift. The following is the Swift code I wrote to split a String into an array of String using Regex:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
    let regex = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions.CaseInsensitive)
    let nsString = text as NSString
    let results = regex.matchesInString(text,
        options: NSMatchingOptions.ReportCompletion , range: NSMakeRange(0, nsString.length))
        as [NSTextCheckingResult]
    return results.map({
        nsString.substringWithRange($0.range)
    })
} catch {
    print("exception")
    return [""]
}

}

When I call the above function with the following:

matchesForRegexInText("(^.*?)\\#\\#(.+$)", text: "blah.clah##something_else")

I get the following:

["blah.clah##something_else"]

I tried several different Regex without success. Is Regex (^. *?) \ # \ # (. + $) Correct, Or is there a problem with matchForRegexInText ()? I appreciate the understanding.

I am using Swift 2 and Xcode Version 7.0 beta (7A120f)

+1
source share
1 answer

, string, regex.matchesInString() NSTextCheckingResult, range . , , , . rangeAtIndex(i) i >= 1:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        guard let result = regex.firstMatchInString(text, options: [], range: NSMakeRange(0, nsString.length)) else {
            return [] // pattern does not match the string
        }
        return (1 ..< result.numberOfRanges).map {
            nsString.substringWithRange(result.rangeAtIndex($0))
        }
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

:

let matches = matchesForRegexInText("(^.*?)##(.+$)", text: "blah.clah##something_else")
print(matches)
// [blah.clah, something_else]
+4

Source: https://habr.com/ru/post/1598564/


All Articles