3

I have a word written in the thai language--> ความรัก How do I use NSRegularExpression to match this word? I tried using the exact word but it is not working.

It is not even working on sites like regex101.com

Here is my code (swift version. But Answers in either swift or obj is appreciated). The following code is in my playground file. I always get false and never true.

let labelString = "ความรัก"
let regex = try NSRegularExpression(pattern: "ความรัก", options: [])
let rangeOfFirstMatch = regex.rangeOfFirstMatchInString(labelString, options:.ReportProgress, range:NSRange(location: 0, length: labelString.characters.count))
if (!NSEqualRanges(rangeOfFirstMatch, NSRange(location: NSNotFound, length: 0))) {
    print(true)
} else {
    print(false)
}

If i replace the texts with the word "man" however. I always get true

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
swift nub
  • 2,747
  • 3
  • 17
  • 39

1 Answers1

8

The flaw resides here:

NSRange(location: 0, length: labelString.characters.count)

NSRegularExpression uses UTF-16 based counts and offsets, so you need to pass a range containing UTF-16 based location and length.

Try changing the line containing the NSRange to this:

let rangeOfFirstMatch = regex.rangeOfFirstMatchInString(labelString,
    options:.ReportProgress,
    range:NSRange(location: 0, length: labelString.utf16.count))

And I prefer this notation (functionality equivalent):

let rangeOfFirstMatch = regex.rangeOfFirstMatchInString(labelString,
    options:.ReportProgress,
    range:NSRange(0..<labelString.utf16.count))

(I'm not sure, but you really need .ReportProgress?)

OOPer
  • 47,149
  • 6
  • 107
  • 142