Error when playing with regex - error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I get an error when I try to access the matches of a regex search, but I can't find where my error is.

Here is the code I'm using in a playground.

import Foundation

let sentence = "There are no strangers, only friends you have not met yet."
let search = "i"
let replace = "ui"
var transformed = sentence
let range = NSRange(transformed.startIndex..., in: transformed)

let regex = try NSRegularExpression(pattern: search, options: [])
let matches = regex.matches(in: transformed, options: [], range: range)
let numberOfMatches = regex.numberOfMatches(in: transformed, options: [], range: range)
matches.forEach({ match in
    if match.numberOfRanges > 0 {
        guard let subrange = Range(match.range(at: 1), in: transformed) else {
        //let substring = transformed[subrange]
        transformed.replaceSubrange(subrange, with: replace)

When I run the code, I get an error at the "matches.forEach" line. I can't see where my error is. Could someone help me?

(Swift 5.4.2, macOS 11.5.2 20G95, Xcode 12.5.1 12E507)

When running your code, I get this:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSSimpleRegularExpressionCheckingResult rangeAtIndex:]: index 1 out of range'
terminating with uncaught exception of type NSException

And debugger clearly stops on the line guard let subrange = Range(match.range(at: 1), .... Not sure why you see it on matches.forEach. Are you debugging release or debug build?

That's the error shown in a playground.
In the real code, the error appear when I run tests for my module.

OK, I found my error. There is no capture group in my regex. But I though that guard should have protected that.

Terms of Service

Privacy Policy

Cookie Policy