iOS正则: 正则匹配中的字符编码

225 阅读1分钟

背景

正则匹配时:遇到字符串中包含𝑃𝐴,𝑃,𝐴𝐵、表情包等特殊字符时,就会匹配失败。

匹配代码:

let text = #"𝑃,𝐴,𝐵是三个点如图:\n![logo](https://images/12122312222_722X463.png)"#
if letregex: NSRegularExpression = try? NSRegularExpression(pattern: #"!\[[^\]]+\]\([^\)]+\)"#, options: .init(rawValue: 0)) {
    let result = regex.matches(in: text, options: .init(rawValue: 0), range: NSRange(location: 0, length: text.count))
    //最终结果 result 为空
}

解决办法

𝑃,𝐴,𝐵等字符在编码时需要两个码点单元来表示其码点值,用String.count给正则匹配range无法获取正确的长度,所以无法匹配,使用String.utf16.count即可

let text = #"𝑃,𝐴,𝐵是三个点如图:\n![logo](https://images/12122312222_722X463.png)"#
if letregex: NSRegularExpression = try? NSRegularExpression(pattern: #"!\[[^\]]+\]\([^\)]+\)"#, options: .init(rawValue: 0)) {
    let result = regex.matches(in: text, options: .init(rawValue: 0), range: NSRange(location: 0, length: text.utf16.count))
    //最终结果 result 达到预期
}

码点与码点单元

码点值:字符的unicode编码值

码点单元:编码一个字符所需的基本单位,如UTF-16一个码点单元占16位即2字节。