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

12,413

Solution 1

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

Solution 2

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.

Solution 3

You can use linq query:

    dim txt as String="badword1 you! you son of a badword2!!"
    dim Badwords() as String = {"badword1","badword2","badword3"} 
    dim result as integer = (from l as string in Badwords where txt.contains(l) select l).count
    if result > 0 then  
       'Whoa.. txt contains some bad vibrations..  
    end if  
Share:
12,413
MilMike
Author by

MilMike

<?php echo "hi"; ?> Hi, my name is Mike. I love to code. Started to code over 20 years ago. I feel at home using a bride spectrum of technologies. Currently I work full time as a web developer in Germany working on PHP/JS projects, but I also developed desktop applications for Windows. Most of the time I work as a backend developer but I also love to work with frontend. If you want to know more about me, just go to my small website or follow me on instagra: My Website Instagram

Updated on June 18, 2022

Comments

  • MilMike
    MilMike almost 2 years

    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?