swift nub swift nub - 3 months ago 13
Swift Question

How do I find words written in Thai with NSRegularExpression

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

Answer

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?)

Comments