Zackline
Zackline

Reputation: 834

Swift 3 extract group from Regex - NS-bridging mess

I am trying to do a simple Regex in Swift 3, extracting a number from the input string.

As I am not familiar with iOS it's proven to be quite a challenge. I highly suspect that my error lies in using both String and NSString simultaneously.

let url = "a5b"
let nsUrl = url as NSString

let regex = try! NSRegularExpression(pattern: "a(\\d)b", options: [])
let matches = regex.matches(in: url, options: [], range: NSRange(location: 0, length: url.characters.count))

somestuff(str: nsUrl.substring(with: matches[1].range))

Fails with the following exception:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

What is the correct way to match and get the number?

Upvotes: 0

Views: 274

Answers (1)

vadian
vadian

Reputation: 285250

Indexes are zero-based but the captured group is at range index 1

somestuff(str: nsUrl.substring(with: matches[0].rangeAt(1)))

You should test for no matches anyway...


About the return value of matches(in:

An array of NSTextCheckingResult objects. Each result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAt(_:) method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.

Note: range is actually the same as rangeAt(0)

Upvotes: 2

Related Questions