0
我正在嘗試使用自由文本字符串搜索數組中的項目。到目前爲止,查看下面的代碼,但我仍然返回僅部分匹配的結果。根據數組中的值在字符串中搜索完全匹配
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"]
你期望什麼?你的鎮數組包含部分字符串。在這種特殊情況下,正則表達式選項是多餘的。 – vadian
我期待只返回「Leamington Spa」和「Coventry」,因爲這些都是搜索文本中指定的城市而非「Leam」,「Lea」或「Cove」。 –