I'm learning Swift, and I'm trying to convert a small bit of JavaScript code to Swift. The JavaScript code uses a Regex to split up a string, as shown below:
var text = "blah.clah##something_else";
var parts = text.match(/(^.*?)\#\#(.+$)/);
after execution, the parts
array will then contain the following:
["blah.clah##something_else", "blah.clah", "something_else"]
I would like to replicate the same behavior in Swift. Below is the Swift code I've written to do split up a String into a String array using a 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've tried a number of different Regex's without success. Is the Regex (^.*?)\#\#(.+$) correct, or is there a problem with the matchesForRegexInText() function? I appreciate any insight.
I'm using Swift 2, and Xcode Version 7.0 beta (7A120f)
let results = regex.matchesInString(text, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, nsString.length)) as Array<NSTextCheckingResult>
? I think the main issue is that you only pass the zeroth group to the array you create withnsString.substringWithRange($0.range)
(i.e. just$0
th group, the whole match). And you do not need to escape#
s. – Imideprint(results.count)
before thereturn
to print out the number of elements in the array, and it is 1. – Encasement