0

什么是在字符串中搜索单词列表的好方法?(不区分大小写)

例子:

def s = "This is a test"

def l = ["this", "test"]

结果可能是对的,也可能是错的,但最好能找到找到的单词数量并且这些单词是......

4

1 回答 1

2

结果可能是对的,也可能是错的,但最好能找到找到的单词数量并且这些单词是......

那么您可能想要findAll该列表中包含在字符串中的单词:D

def wordsInString(words, str) {
    def strWords = str.toLowerCase().split(/\s+/)
    words.findAll { it.toLowerCase() in strWords }
}

def s = "This is a test"
assert wordsInString(["this", "test"], s) == ["this", "test"]
assert wordsInString(["that", "test"], s) == ["test"]
assert wordsInString(["that", "nope"], s) == []

// Notice that the method conserves the casing of the words.
assert wordsInString(["THIS", "TesT"], s) == ["THIS", "TesT"]

// And does not match sub-words.
assert wordsInString(["his", "thi"], s) == []

而且,由于列表具有与之关联的真值if (wordsInString(someWords, someString)) { ... },因此您可以直接在布尔上下文中使用结果,例如.

于 2013-03-07T22:05:27.927 回答