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)
source
share