2017-03-27 46 views
2

給出的單詞(和它們的複數)的列表,以尋找:如何獲取包含屬於數組的單詞的字符串的開始?

let array = ["\\b(ab+?)(s\\b|\\b)", "\\b(cd+?)(s\\b|\\b)", "\\b(ef+?)(s\\b|\\b)", "\\b(gh+?)(s\\b|\\b)"] 

這是短期的:

let words = ["ab", "cd", "ef", "gh"] 
let array = words + words.map {$0 + "s"} 

我想所有的句子的單詞。從字符串的開頭,高達滿足正則表達式最後一個字開始。從array或其複數形式應該匹配的每個元素(通過添加 「S」,IES複數不考慮):

例如:

let string_1 = "abc ab def cds ghi jkl bs mno" // should get "abc ab def cds" 
let string_2 = "abc ghs def" // should get "abc ghs" 
let string_3 = "abc ab def bc ghi" // should get "abc ab" 
let string_4 = "abc def" // should get "" or nil 

我的當前的想法是:

let words = string_1.components(separatedBy: CharacterSet.whitespacesAndNewlines) 
let lastOccurrence: (Int, String)? = words.enumerated().reversed().first(where: { (index, value) in 
    if let _ = restOfSentence.range(of: value, options: .regularExpression) { 
     return true 
    } 
    return false 
}) 

if let l_o = lastOccurrence { 
    let matchingWordsArray = words[0...l_o.0] 
    let matchingWords = matchingWordsArray.joined(separator: " ") 
    print(matchingWords) 
} 

打破一句成詞,然後加入他們似乎貴了我。
有沒有更好的方法來做到這一點?

+0

您可以形成一個正則表達式,比如'讓拍=「^ [ABCD] {1, 4} S'\\灣* \\ b [ABCD] {1,4} S'\\ b「​​'。如果''a「'等是多字符單詞,則必須使用分組:'^(?: a | b | c | d){1,4} s?\ b。* \ b(?: A | b | C | d){1,4}Š\ B'?。但是,如果你想允許匹配諸如'aaa'的東西,目前還不清楚。可能會發現,正則表達式方法畢竟不是最好的。 –

+0

是@WiktorStribiżew我想全字匹配 – Carpsen90

+0

你的正則表達式不'string_1'匹配'abc'。你真的想做什麼? – OOPer

回答

0

你可以使用NSRegularExpression(雖然我覺得它的快速實施是煩人充滿老NSRange/NSString的相關性):

let string_1 = "abc ab def cds ghi jkl bs mno" // should get "abc ab def cds" 
let string_2 = "abc ghs def" // should get "abc ghs" 
let string_3 = "abc ab def bc ghi" // should get "abc ab" 
let string_4 = "abc def" // should get "" or nil 


let array = ["\\b(ab+?)(s\\b|\\b)", "\\b(cd+?)(s\\b|\\b)", "\\b(ef+?)(s\\b|\\b)", "\\b(gh+?)(s\\b|\\b)"] 

func matchingWords(_ string:String, patterns:[String]) -> String 
{ 
    let anyPattern = patterns.map{"("+$0+")"}.joined(separator:"|") 

    let string = NSString(string:string) 
    let fullRange = NSMakeRange(0,string.length) 

    if let regEx  = try? NSRegularExpression(pattern:anyPattern, options:.caseInsensitive), 
     let lastRange = regEx.matches(in:string as String, range:fullRange).last?.range 
    { 
    return string.substring(to: lastRange.location + lastRange.length) 
    } 

    return "" 
} 

print(matchingWords(string_1, patterns:array)) // abc ab def cds 
print(matchingWords(string_2, patterns:array)) // abc gh 
print(matchingWords(string_3, patterns:array)) // abc ab 
print(matchingWords(string_4, patterns:array)) // <empty string> 
+0

我的解決方案在大量字符串上仍然更快 – Carpsen90

相關問題