我正在尝试使用自由文本字符串搜索数组中的项目。我到目前为止,请看下面的代码,但我仍然会返回仅部分匹配的结果。
var townArray = ["Leamington Spa", "Birmingham", "Coventry", "Leamington Hastings", "Royal Leamington Spa", "Lea", "Leam", "Cove"]
let searchText = "Anyone want to meet in Leamington Spa or Coventry"
var resultsArray = [String]()
for i in townArray {
let range = searchText.lowercased().range(of: i.lowercased(), options: .regularExpression)
// (8 times)
if range != nil {
let found = searchText.substring(with: range!)
print(found)
resultsArray.append(found)
// (5 times)}
}
print(resultsArray)
// ["Leamington Spa", "Coventry", "Lea", "Leam", "Cove"]
答案 0 :(得分:1)
确切的单词匹配并不简单,您可能需要使用正则表达式。
例如:
var townArray = ["Leamington Spa", "Birmingham", "Coventry", "Leamington Hastings", "Royal Leamington Spa", "Lea", "Leam", "Cove"]
let searchText = "Anyone want to meet in Leamington Spa or Coventry"
let townRegexArray = townArray.map {townName -> (name: String, regex: NSRegularExpression) in
let pattern = townName.components(separatedBy: " ")
.map{"\\b"+NSRegularExpression.escapedPattern(for: $0)+"\\b"}
.joined(separator: "\\s+")
//print(pattern) //->\bLeamington\b\s+\bSpa\b (=="\\bLeamington\\b\\s+\\bSpa\\b")...
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
return (name: townName, regex: regex)
}
let resultsArray = townRegexArray
.filter{$0.regex.firstMatch(in: searchText, range: NSRange(0..<searchText.utf16.count)) != nil}
.map{$0.name}
print(resultsArray) //->["Leamington Spa", "Coventry"]
\b
(String literal中的"\\b"
)表示正则表达式中的单词边界。因此\bLeam\b
与Leamington
不匹配。
答案 1 :(得分:0)
你会做这样的事情
constant