2016-12-20 77 views
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"] 
+0

你期望什麼?你的鎮數組包含部分字符串。在這種特殊情況下,正則表達式選項是多餘的。 – vadian

+0

我期待只返回「Leamington Spa」和「Coventry」,因爲這些都是搜索文本中指定的城市而非「Leam」,「Lea」或「Cove」。 –

回答

0

你會做這樣的事

let matchingStrings = resultsArray.filter { $0 == "TARGET_STRING" } 
let containsString = !matchingStrings.isEmpty 
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(在字符串文字"\\b")表示的正則表達式字邊界。所以\bLeam\bLeamington不匹配。