I am using the Swift Playground to experiment with NSRegularExpression
and I do not get what I would like to.
Here is my code:
import UIKit
let str = "qwun782h218gs634 AbCd56EfGh7ZsDe985\nXzSr519UkGe9823SdFg91nui uihiheg875d dss77ds",
patn = "(([A-Z][a-z]){2}([0-9]+)){3}",
rgx = try! NSRegularExpression(pattern: patn, options: .AnchorsMatchLines)
print("Start with:\(str)")
let strNS = str as NSString
rgx.enumerateMatchesInString(str, options: .ReportCompletion,
range: NSMakeRange(0,str.utf8.count),
usingBlock: { (result, _, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let _ = result?.range.location {
var n = 0,
theStr = strNS.substringWithRange(NSMakeRange((result?.rangeAtIndex(n).location)!,
(result?.rangeAtIndex(n).length)!))
print("xpr [\(n)]: \(theStr)")
n = 1
theStr = strNS.substringWithRange(NSMakeRange((result?.rangeAtIndex(n).location)!,
(result?.rangeAtIndex(n).length)!))
print("xpr [\(n)]: \(theStr)")
n = 2
theStr = strNS.substringWithRange(NSMakeRange((result?.rangeAtIndex(n).location)!,
(result?.rangeAtIndex(n).length)!))
print("xpr [\(n)]: \(theStr)")
n = 3
theStr = strNS.substringWithRange(NSMakeRange((result?.rangeAtIndex(n).location)!,
(result?.rangeAtIndex(n).length)!))
print("xpr [\(n)]: \(theStr)")
}
})
This is what I get in the result console:
Start with:qwun782h218gs634 AbCd56EfGh7ZsDe985
XzSr519UkGe9823SdFg91nui uihiheg875d dss77ds
xpr [0]: AbCd56EfGh7ZsDe985
xpr [1]: ZsDe985
xpr [2]: De
xpr [3]: 985
xpr [0]: XzSr519UkGe9823SdFg91
xpr [1]: SdFg91
xpr [2]: Fg
xpr [3]: 91
Finally here is what I am interested in:
xpr: 56
xpr: 7
xpr: 985
xpr: 519
xpr: 9823
xpr: 91
In other words I want to capture all the groups of numbers.
In this example, I could of course change the shape of my regular expression, get rid of the {2} and {3} and make it work (by extending it). But this is not what I want and this is the purpose of my question. How can I keep this compacted form of the regular expression, while being able to capture what I want?
If instead of {2} and {3}, I had {12} and {37}; nobody would like to extend the expression :)