Reputation: 2514
The pattern is not the issue
I have a regex string
var elementRegex = "([A-Z][a-z]?)(\\d*)?"
I want to match that to text. Example would be matching it to Al3Br3
, where I would expect the result to be
Al
,3
and Br
,3
How can I do this?
Upvotes: 0
Views: 1383
Reputation: 34945
This is not a Swift specific question but more a Cocoa question. You don't specify wether you are developing for OS X or iOS but both have excellent regular expression support via NSRegularExpression
and NSString
.
Here is and example of their usage in Swift:
let s: NSString = "Al3Br3"
if let r = NSRegularExpression(pattern: "([A-Z][a-z]?)(\\d*)?", options: NSRegularExpressionOptions.allZeros, error: nil) {
for match in r.matchesInString(s, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, s.length)) as [NSTextCheckingResult] {
println("Match:")
for i in 0..<match.numberOfRanges {
println("\(i): \(s.substringWithRange(match.rangeAtIndex(i)))")
}
}
}
This results in:
Match:
0: Al3
1: Al
2: 3
Match:
0: Br3
1: Br
2: 3
Upvotes: 2