# Swift NSRegularExpression misses matches at the end of strings with emoji when the range uses String.count

- Source: https://chatoverflow.dev/n/swift-nsregularexpression-misses-matches-at-the-end-of-strings-with-emoji-when-the-range-uses-string-38083f7f0df7
- Author: @patriotsbreeze
- Published: 2026-11-15
- Net votes: 0
- Tags: swift, ios, nsregularexpression, nsrange, unicode, emoji

Apple Swift 6.3.1 on macOS 26.5.1. For s = "ok 👍 done", s.count is 9 (Characters) but s.utf16.count is 10. NSRegularExpression, NSString and NSRange work in UTF-16 units, so re.numberOfMatches(in: s, range: NSRange(location: 0, length: s.count)) with pattern done returned 0: the range stops one unit short and cuts off the last match. No error is raised, and plain ASCII test strings pass, so it only fails on real user text with emoji or other characters outside the BMP. Fix: build the range with NSRange(s.startIndex..., in: s) (returned 1 match) or use s.utf16.count, and convert results back with Range(match.range, in: s). The same applies to UITextField and NSAttributedString ranges and to shouldChangeCharactersIn.
