我有一个字符串列表中的单词列表
List<String> badWords = [
"bad",
"damn",
//and other list of offensive words too
];
现在如果我有一个字符串是通过输入从用户那里得到的,我想循环遍历列表并检查这些单词是否与字符串上的任何单词匹配也许可以使用regex eg
String text = msgController.text;
badWords.map((e) {
//If any the words in the text matches any of the words in the list then print those words out
}).toList();
我建议拆分句子,看看数组中是否包含坏单词。为了使它更花哨,我们可以使用regex按多个字符分割。下面是带有注释的完整工作示例:
void main() {
List<String> badWords = [
"bad", "damn", //and other list of offensive words too
];
List<String> sentences = [
"bad developer, you broke production",
"good dev, you did good job",
"damn devs, they brake stuff"
];
for(String sentence in sentences){
if(isSentenceOffensive(sentence, badWords)){
print('$sentence - is offensive!');
}
}
}
bool isSentenceOffensive(String sentence, List<String> badWords)
{
/* here we use regex to split by either dot (.), comma (,), or space ( ) */
List<String> words = sentence.split(RegExp(r"[., ]"));
for (String word in words){
if(badWords.contains(word)){
return true;
}
}
return false;
}
以上输出为:
bad developer, you broke production - is offensive!
damn devs, they brake stuff - is offensive!
我将简单地遍历列表并检查字符串是否包含任何单词。
String text = msgController.text
for (var i in badWords) {
if (text.contains(i)){
// Do something
}
}
其他答案非常准确,.contains()
是我用来检查badWords
列表的。如果您在空格上分割text
并将其存储在另一个列表中,您可以遍历该列表并检查badWords
列表中是否存在每个单词。下面是一种可能的方法:
List<String> badWords = [
"bad",
"damn",
// and other list of offensive words too
];
String text = msgController.text;
final textWords = text.split(' ');
for(final word in textWords) {
if (badWords.contains(word.toLowerCase())) {
// do a thing with the bad word
print(word);
}
}
同样值得注意的是,通过迭代文本而不是badWords
,您可以调用.toLowerCase()
来确保您正在检查不区分大小写的坏单词(只要您将badWords
中的所有值都以小写存储)。
我将使用RegExp,因为它提供了一种只匹配整个单词的方法,并且您不想禁止像" admin "这样的字符串。或";assassin"就因为里面有脏话。它还可以很容易地忽略大小写,这也是您可能想要做的。
var badWordsRE = RegExp("\b(?:${badWords.join("|")})\b", caseSensitive: false);
bool containsBadWords = badWordsRE.hasMatch(string);
b
只匹配一个词边界,所以"bad"
不会在"badminton"
中找到。
这假设badWords
列表只包含在RegExp中没有意义的字母和符号,所以如果您试图捕获ASCII艺术或类似的,您可能需要转义它们:
var badWordsRE = RegExp(
"\b(?:${badWords.map(RegExp.escape).join("|")})\b",
caseSensitive: false);
可以使用list.contains(x)
;
更多信息请点击此处。
void main()
{
List<String> stringlist = [
// list of string data. here is the name
'zeshan',
'abid',
'ali',
];
// "zeshan" is the new string
print(stringlist.contains('zeshan'),);
}
结果将是…真的。