這是一個有點像試圖找到一個列表中的子表,所以一個辦法是既轉換成單詞表,如下:
wordlist.split(" ") containsSlice words.split(" ")
從REPL,它看起來像這樣符合你的要求(如果不是,請展開!):
scala> def hasPhrase(wordList:String,words:String) = wordList.split(" ") containsSlice words.split(" ")
hasPhrase: (wordList: String, words: String)Boolean
scala> hasPhrase("value of this","value")
res13: Boolean = true
scala> hasPhrase("value of this","value of")
res14: Boolean = true
scala> hasPhrase("value of this","val")
res15: Boolean = false
scala> hasPhrase("value of this","his")
res16: Boolean = false
拆分兩個字符串不會是跨大串或大量字符串進行高效。如果你的用例允許,你可以只分割一次長句(所以你可以做wordlistAsCollection containsSlice words.split(" ")
)。您也可以嘗試一個正則表達式的方法,因爲在評論中建議,也許線沿線的:
def hasPhrase(wordList:String,words:String) =
new scala.util.matching.Regex("\\b"+words+"\\b")
.findFirstMatchIn(wordList)
.isDefined
[scala完全匹配給定字符串中的單詞]的可能重複(http://stackoverflow.com/questions/13652447/scala-exactly-matching-a-word-in-a-given-string) –
使用'\ b' +'單詞'+'\ b',或'(?<!\ S)'+'單詞'+'(?!\ S)'。你可以解釋一下這個嗎? –
? –