String.Contains(Array?..) - VB.NET中的Badword过滤器

Mil*_*ike 4 vb.net arrays string

有没有办法检查String是否包含数组中的项目之一?像这样:

dim txt as String="badword1 you! you son of a badword2!!"
dim Badwords() as String = {"badword1","badword2","badword3"}
if txt.contains(Badwords()) then
'Whoa.. txt contains some bad vibrations..
end if
Run Code Online (Sandbox Code Playgroud)

我可以使用循环但是如果它包含数组中的一个字符串,我可以检查一个字符串吗?

Sat*_*tal 11

我认为这应该做你想要的

Dim txt As String = "badword1 you! you son of a badword2!!"
Dim Badwords() As String = {"badword1", "badword2", "badword3"}

If Badwords.Any(Function(b) txt.ToLower().Contains(b.ToLower())) Then
    'Whoa.. txt contains some bad vibrations..
    MessageBox.Show("You said a naughty word :P")
End If
Run Code Online (Sandbox Code Playgroud)

你需要 Import System.Linq


Nik*_*cke 7

循环是最简单的方法.

但是,如果您担心速度而不是易读性,则可以使用单个正则表达式替换整个数组.

我对基本语法(有点生疏)不太好,但有些像......

dim badwords as Regex = new Regex("badword1|badword2|badword3");
if badwords.IsMatch(txt) then
Run Code Online (Sandbox Code Playgroud)

如果单词列表是固定的,那么最好将badwords变为静态.(这是它们在Basic中调用的吗?我的意思是一个变量,它只在程序的生命周期中初始化一次,而不是每次使用它.)你可以在Regex构造函数中设置一个Compiled标志来加速更进一步(表达式在创建时编译,而不是在使用时编译).

Regex位于System.Text.RegularExpressions命名空间中.