NSRange in string

I have a string and an NSRegularExpression instance:

let string = "example string"
let regex = try! NSRegularExpression(pattern: #"(example) (string)"#)

When I try to find the first match using firstMatch(in:options:range:), how do I get the range parameter correctly?

let match = regex.firstMatch(
    in: string, 
    range: NSRange(location: 0, length: string.count)
)
// or
let match = regex.firstMatch(
    in: string, 
    range: NSRange(location: 0, length: string.lengthOfBytes(using: .utf8))
)
// or
let match = regex.firstMatch(
    in: string, 
    range: NSRange(location: 0, length: string.lengthOfBytes(using: .utf16))
)

I can't find much of any useful documentation on NSRange, other than that it "describe a portion of a series, such as characters in a string".

Given that NSString.length are on UTF-16 code units, and the numberOfMatches example uses it in the NSRegularExpression page, I'll guess the same goes for other ranges.

2 Likes

That’s correct. Fortunately, there are NSRange/Range converting initializers (in both directions) that take a string as context.

1 Like

Thanks for the tip. Found this one through auto-completion (no documentation): NSRange.init(region:in:), which seems like a much better option than init(location:length:).