Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Contains(Array?..) - Badword Filter in VB.NET

is there a way to check if a String contains one of the item in array? like this:

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

I could use a loop but is there maybe a faster method how I can check a string if it contains one of the strings in the array?

like image 806
MilMike Avatar asked Dec 02 '22 01:12

MilMike


2 Answers

I think this should do what you want

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

You'll need to Import System.Linq

like image 131
Sam Jenkins Avatar answered Dec 18 '22 21:12

Sam Jenkins


A loop is the simplest way.

However, if you are concerned about speed rather than legibility, you could replace the whole array with a single regular expression.

I'm not that good with Basic syntax (a bit rusty), but something like...

dim badwords as Regex = new Regex("badword1|badword2|badword3");
if badwords.IsMatch(txt) then

If the list of words is fixed, it would be best to make badwords a static. (Is that what they are called in Basic? I mean a variable which is only initialised once in the life of the program, not every time it is used.) There is a Compiled flag you can set in the Regex constructor which would speed things up even further (the expression is compiled when it is created, rather than when it is used).

Regex is found in the System.Text.RegularExpressions namespace.

like image 40
Nikki Locke Avatar answered Dec 18 '22 23:12

Nikki Locke