Reputation: 294
I use a code from Swift extract regex matches
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, 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 []
}
}
I try match this pattern (sample pattern) "^([a-z]+).*?(\d+)$"
And if I use it for string "abc.....123" I get as result this full string...
But I want to get array of strings ["abc", "123"]
Upvotes: 0
Views: 435
Reputation: 285059
You have to get the subranges of the captured groups – the expressions of the regex within the parentheses respectively – with rangeAtIndex()
of the first match.
Since the range of the full string is at index 0, start the loop at index 1.
func matchesForRegexInText(regex: String, text: String) -> [String] {
var result = [String]()
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
if let match = regex.firstMatchInString(text, options: [], range: NSMakeRange(0, nsString.length)) {
for i in 1..<match.numberOfRanges {
result.append(nsString.substringWithRange(match.rangeAtIndex(i)))
}
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
}
return result
}
PS: Not everything in Swift needs a ?
or !
. The exclamation marks in the parameter strings are meaningless as none of them is actually considered as optional.
Upvotes: 1