ios - Working out a difficult case with NSRegularExpression -
i using swift playground experiment nsregularexpression
, not to. here 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 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 in 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 interested in:
xpr: 56 xpr: 7 xpr: 985 xpr: 519 xpr: 9823 xpr: 91
in other words want capture groups of numbers.
in example, of course change shape of regular expression, rid of {2} , {3} , make work (by extending it). not want , purpose of question. how can keep compacted form of regular expression, while being able capture want?
if instead of {2} , {3}, had {12} , {37}; nobody extend expression :)
actually regex \\d+
(one numeric character or more) sufficient.
let patn = "\\d+" let str = "abcd56efgh7zsde985\nxzsr519ukge9823sdfg91", rgx = try! nsregularexpression(pattern: patn, options: []) print("start with:\(str)") rgx.enumeratematchesinstring(str, options: [], range: nsrange(location:0, length:str.characters.count)) { (result, _, _) in if result != nil { print("xpr: \((str nsstring).substringwithrange(result!.range))") } }
Comments
Post a Comment