Range string return incorrect with regularExpression option when we run in iOS 17 developer beta.

Hi, I'm an iOS developer who found an issue with the regularExpression option in the range method of the string. The return value differs between iOS 17 beta 1 and iOS 16, even when using the same regex pattern and input.

Build with XCode14.2

// Regex pattern to check thousand amount pattern but comma is optional.
// 10000 => Correct
// 1000,0 => Incorrect
let regex = "^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*$"
let rangeOf10000 = "10000".range(of: regex, options: .regularExpression)
let rangeOf100000 = "100000".range(of: regex, options: .regularExpression)

// in iOS 17.0 developer beta
// rangeOf10000 = nil
// rangeOf100000 = got an object normally.

// in iOS 16.2
// rangeOf10000 = got an object normally.
// rangeOf100000 = got an object normally.

I don't know if the defect in the range method or my missing something in the regex pattern such a long time, but I wonder why rangeOf10000 is nil in iOS 17 beta 1.

First up, you should definitely file a bug about this. Foundation is meant to be binary compatible from release to release and clearly that’s not happening here.

Please post your bug number, just for the record.

As to what’s going wrong, I suspect that Foundation has moved to the Swift native regex engine. If you convert your code to Swift regexes, you see the same behaviour on earlier systems (I’m testing from a command-line tool on macOS 13.3.1).

As to why it’s going wrong, I suspect it has something to do with backtracking. Your regex requires a lot of it because of the way it’s structured.

You might be better off doing your matching in reverse, that is, reversing the string and reversing the regex. I think that’ll eliminate virtually all the backtracking. So, something like this:

let regex = "^(?:[0-9]{3},?)*[0-9]{1,3}[+-]?$"
let reversed = String(input.reversed())
let r = reversed.range(of: regex, options: .regularExpression)
print("'\(input)' -> \(r.map { String(reversed[$0].reversed()) } ?? "-")")

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Bug report number: FB12283090

any update on this bug?

Range string return incorrect with regularExpression option when we run in iOS 17 developer beta.
 
 
Q