finding exact matches in strings

manared

Well-known member
Joined
Jun 1, 2006
Messages
84
Programming Experience
1-3
I'm creating a web app in vb.net 2005. I have 2 variables, one is just a word (variable x) and the other is a phrase/sentence (variable y). I need to see if the variable x is found in variable y. But, say x is "free" and y is "I am freezing." So far, I've been trying to match these and it is true, but that is not what I want. Yes, "free" is in "freezing" but I want only the full word by itself. For example, this should come back as true ("This object is free") whereas this one should not ("I'm going to freeze"). Any ideas? Maybe with regular expressions or matching or parsing or anything like that? Thank you much!!
 
Regular expression does this fine:
VB.NET:
Dim input As String = "freeway isn't free!"
Dim pattern As String = "\bfree\b"
Dim m As System.Text.RegularExpressions.Match
m = System.Text.RegularExpressions.Regex.Match(input, pattern)
MsgBox(m.Captures(0).Value)
MsgBox(m.Captures(0).Index.ToString)
MsgBox(m.Captures(0).Length.ToString)
It can also be done only with string functions like this:
VB.NET:
Dim search As String = "free"
Dim delims As String = " -.,_:;+!#&/\^=*?[]{}()%$£@§<>"
Dim words() As String = input.Split(delims.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
For Each word As String In words
  If word = search Then
    MsgBox("found")
    Exit For
  End If
Next
 
Thanks for your reply. I actually figured it out a little while ago, forgot to post it though. This is the way I'm doing it right now:

VB.NET:
campaign = ds.Tables(0).Rows(i).Item("campaign_text").ToString
If System.Text.RegularExpressions.Regex.Matches(SMS, "\b" & campaign & "\b").Count > 0 Then
isMatch = True
lblTest.Text = "Match found"
lblX.Text = campaign
lblY.Text = SMS
campaignId = ds.Tables(0).Rows(i).Item("campaign_id").ToString
companyId = ds.Tables(0).Rows(i).Item("company_id").ToString
Exit For
End If

This is something else that I tried (and works, but it's slower) that is very similar to your solution as well:

VB.NET:
Dim matching As Boolean
Dim sites As String() = Nothing
sites = y.Split(" ")
Dim s As String
For Each s In sites
matching = x Like s
If matching = True Then
lblTest.Text = "They match!"
lblX.Text = x
lblY.Text = s
End If
Next s

Both of these ways work, but I'm using the first one because with as much data as I have to loop through, it goes much faster. Thanks for your input!!
 
Back
Top