regex - How to find which group is matched in NSRegularExpression -
i have regex statement multiple capture groups separated | operator. how can find out capture group matched? way can think of -for example- counting number of characters if matched.
var string = "1234567897" var pattern = "(^\\d{9}$)|(^\\d{10}$)|(^\\d{13}$)|(^[a-za-z]{2}\\d{9}[a-za-z]{2}$)" var myregex = nsregularexpression(pattern: pattern, options: nil, error: nil)! if let mymatch = myregex.firstmatchinstring(string, options: nil, range: nsrange(location: 0, length: string.utf16count)) { println((string nsstring).substringwithrange(mymatch.rangeatindex(0))) }
i wrote code worked example. sure can written better way works now.
swift 2.3
var string = "123456789" var pattern = "(^\\d{9}$)|(^\\d{10}$)|(^\\d{13}$)|(^[a-za-z]{2}\\d{9}[ww]{2}$)" var myregex = try! nsregularexpression(pattern: pattern, options: []) if let mymatch = myregex.firstmatchinstring(string, options: nsmatchingoptions.init(rawvalue: 0), range: nsrange(location: 0, length: string.utf16.count)) { var matchedgroup = 0 var in 1..<mymatch.numberofranges { if mymatch.rangeatindex(i).length != 0 { matchedgroup = break } } print(matchedgroup) print((string nsstring).substringwithrange(mymatch.rangeatindex(0))) //whatever range want print }
swift 3
var string = "123456789" var pattern = "(^\\d{9}$)|(^\\d{10}$)|(^\\d{13}$)|(^[a-za-z]{2}\\d{9}[ww]{2}$)" var myregex = try! nsregularexpression(pattern: pattern, options: []) if let mymatch = myregex.firstmatch(in: string, options: nsregularexpression.matchingoptions.init(rawvalue: 0), range: nsrange(location: 0, length: string.utf16.count)) { var matchedgroup = 0 var in 1..<mymatch.numberofranges { if mymatch.rangeat(i).length != 0 { matchedgroup = break } } print(matchedgroup) print((string nsstring).substring(with: mymatch.rangeat(0))) //whatever range want print }
Comments
Post a Comment