• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

Is Regex the best way to do simple pattern matching in VB?

Is Regex the best way to do simple pattern matching in VB.NET.

Here I'm check in the string has the word News in it.

            Dim objMatch As Match

            objMatch = Regex.Match("News", sSave.ToString)

            If (objMatch.Success) Then
                '     sSave = "Got News"
            End If
0
vaultworld
Asked:
vaultworld
  • 2
  • 2
2 Solutions
 
rlh68Commented:

I use IndexOf for simply searching.

    Dim str As String = "Some text to search for the word News in."
        If Str.IndexOf("News") > 0 Then
            ' has news, do something
        End If
0
 
vaultworldAuthor Commented:
Thanks,  it does have a weakness.

If the string is the same size that your looking for it doesn't work.

Example looks for News inside of News
0
 
ZippitCommented:
actually...it does.  In the previous example, change the following line:

If Str.IndexOf("News") > 0 Then

To:

If Str.IndexOf("News") >= 0 Then

The it will work, even when searching for "News" inside of "News" (IndexOf returns -1 if no match, 0 if match is found at first character).

HTH
0
 
ZippitCommented:
IndexOf is the way to go if you are looking for a simple string within another string.  Don't get RegEx unless you are looking for more complex patterns (like multiple strings separated by any number of characters, patterns, etc).
0
 
vaultworldAuthor Commented:
Thanks a ton, both of you
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now