I am new to swift and looking for an efficient way to separate a string into an array based on regex matched.
In Ruby it is a one line command
irb(main):006:0> number = "(123) 456-7890"
=> "(123) 456-7890"
irb(main):007:0> number.scan(/(\w+)/).join()
=> "1234567890"
irb(main):008:0>
In Swift, it was complicated and I used this function from an answer here Swift extract regex matches to separate the components into a String array. The join works the same way, so that's at least good. Is there a scan function in swift? If not, how can I create a global function that I can use.
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
let regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)!
let nsString = text as NSString
let results = regex.matchesInString(nsString as String,
options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
return map(results) { nsString.substringWithRange($0.range)}
}
var number = "(123) (456) 7890"
var wordArr = matchesForRegexInText("\\w+", number)
join("",wordArr) #> "1234567890"