gpt4 book ai didi

iOS - 匹配单词边界的正则表达式,包括下划线

转载 作者:搜寻专家 更新时间:2023-11-01 06:42:15 25 4
gpt4 key购买 nike

我有一个正则表达式,我试图运行它来匹配各种搜索词。例如:

搜索“old”应该匹配:-> age_old-> old_age但不是-> 粗体 - 因为它不在单词的开头

为此,我使用了单词边界。但是,单词边界不考虑下划线。如前所述 here , 有其他语言的解决方法。不幸的是,使用 NSRegularExpression,这看起来是不可能的。还有其他方法可以使单词边界起作用吗?还是其他选择?

最佳答案

Swift 和 Objective C 支持 ICU regex flavor .这种风格支持固定和受限宽度的后视。

(?= ... )    Look-ahead assertion. True if the parenthesized pattern matches at the current input position, but does not advance the input position.

(?! ... )    Negative look-ahead assertion. True if the parenthesized pattern does not match at the current input position. Does not advance the input position.

(?<= ... )    Look-behind assertion. True if the parenthesized pattern matches text preceding the current input position, with the last character of the match being the input character just before the current position. Does not alter the input position. The length of possible strings matched by the look-behind pattern must not be unbounded (no * or + operators.)

(?<! ... )    Negative Look-behind assertion.

所以,你可以使用

 let regex = "(?<![\\p{L}\\d])old(?![\\p{L}\\d])";

参见 regex demo

这是一个Swift code snippet提取所有“旧”:

func matchesForRegexInText(regex: String, text: String) -> [String] {

do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}

let s = "age_old -> old_age but not -> bold"
let rx = "(?<![\\p{L}\\d])old(?![\\p{L}\\d])"
let matches = matchesForRegexInText(rx, text: s)
print(matches) // => ["old", "old"]

关于iOS - 匹配单词边界的正则表达式,包括下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com