这是一个有点像试图找到一个列表中的子表,所以一个办法是既转换成单词表,如下:
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)'。你可以解释一下这个吗? –
? –