我正在尝试匹配用户输入中的粗鲁单词,例如"I Hate You!"或"i.håté.Yoù"将与从JSON解析的单词数组中的"hate you"匹配。
所以我需要它对大小写和变音符号不敏感,并将粗鲁单词中的空格视为任何非字母字符:正则表达式元字符P{L}
应该为此工作,或者至少W
现在我知道[cd]
适用于NSPredicate
,就像这样:
func matches(text: String) -> [String]? {
if let rudeWords = JSON?["words"] as? [String]{
return rudeWords.filter {
let pattern = $0.stringByReplacingOccurrencesOfString(" ", withString: "\P{L}", options: .CaseInsensitiveSearch)
return NSPredicate(format: "SELF MATCHES[cd] %@", pattern).evaluateWithObject(text)
}
} else {
log.debug("error fetching rude words")
return nil
}
}
这不适用于任何元字符,我想它们不会被NSpredicate
解析,所以我尝试使用这样的NSRegularExpression
:
func matches(text: String) -> [String]? {
if let rudeWords = JSON?["words"] as? [String]{
return rudeWords.filter {
do {
let pattern = $0.stringByReplacingOccurrencesOfString(" ", withString: "\P{L}", options: .CaseInsensitiveSearch)
let regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
return regex.matchesInString(text, options: [], range: NSMakeRange(0, text.characters.count)).count > 0
}
catch _ {
log.debug("error parsing rude word regex")
return false
}
}
} else {
log.debug("error fetching rude words")
return nil
}
}
这似乎工作正常,但是我知道无法使正则表达式变音符号不敏感,所以我尝试了这个(以及其他解决方案,如重新编码)
let text = text.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
但是,这对我不起作用,因为我每次键入字符时都会检查用户输入,因此我尝试去除重音的所有解决方案都使应用程序非常慢。
有人知道是否有任何其他解决方案,或者我是否以错误的方式使用它?
谢谢
编辑
我实际上错了,使应用程序变慢的是试图与P{L}
匹配,我尝试了带有W
和重音剥离行的第二个解决方案,现在即使它匹配的字符串比我最初想要的要少,它也可以正常工作。
链接
这些可能有助于一些人处理正则表达式和谓词:
- http://www.regular-expressions.info/unicode.html
- http://juehualu.blogspot.fr/2013/08/ios-notes-for-predicates-programming.html
- https://regex101.com
个方向可能是值得的。而不是扁平输入,如果你改变正则表达式怎么办?
例如,不是与hate.you
匹配,而是可以与[h][åæaàâä][t][ëèêeé].[y][o0][ùu]
匹配(无论如何,它不是一个完整的列表)。动态执行此转换(而不是存储它)是最有意义的,因为如果您需要更改字符稍后扩展的内容,这可能会更容易。
这将使您可以更好地控制将匹配哪些字符。如果你看,我有0
作为角色匹配o
.再多的Unicode强制都不能让你这样做。
我最终使用了劳雷尔建议的解决方案。它对我来说效果很好。
我把它贴在这里给任何可能需要它的人。
extension String {
func getCaseAndDiacriticInsensitiveRegex() throws -> NSRegularExpression {
var pattern = self.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
pattern = pattern.replacingOccurrences(of: "a", with: "[aàáâäæãåā]")
pattern = pattern.replacingOccurrences(of: "c", with: "[cçćč]")
pattern = pattern.replacingOccurrences(of: "e", with: "[eèéêëēėę]")
pattern = pattern.replacingOccurrences(of: "l", with: "[lł]")
pattern = pattern.replacingOccurrences(of: "i", with: "[iîïíīįì]")
pattern = pattern.replacingOccurrences(of: "n", with: "[nñń]")
pattern = pattern.replacingOccurrences(of: "o", with: "[oôöòóœøōõ]")
pattern = pattern.replacingOccurrences(of: "s", with: "[sßśš]")
pattern = pattern.replacingOccurrences(of: "u", with: "[uûüùúū]")
pattern = pattern.replacingOccurrences(of: "y", with: "[yýÿ]")
pattern = pattern.replacingOccurrences(of: "z", with: "[zžźż]")
return try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
}
}