Vo Kim Nguyen Vo Kim Nguyen - 1 year ago 76
Swift Question

Get a match string in (.*) with NSRegularExpression

I'm using Swift 2, and trying to get a number from a HTML data response from URL, dataString is my HTML text, I use NSRegularExpression and try to get string

let patten = "<span class=bld>(.*)USD</span>"
let reg = try? NSRegularExpression(pattern: patten, options: NSRegularExpressionOptions.init(rawValue: 0))
let rangeMatch = reg?.firstMatchInString(dataString, options: [], range: NSMakeRange(0, dataString.characters.count))
if rangeMatch != nil {
let res = (dataString as! NSString).substringWithRange((rangeMatch?.range)!)

But the result I got is full string
<span class=bld>22309 USD</span>
, I'm only want to get
number. Anyone could show me how to get it please ?

Answer Source

Captured groups are located at range index 1+ of the NSTextCheckingResult object.


I recommend a more specific pattern:

let pattern = "<span class=bld>(\\d+)\\sUSD</span>"

or still shorter

let pattern = "(\\d+)\\sUSD"

\\d+ is one or more digits, \\s is a whitespace character

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download