Using Regular Expressions with VB.NET


At the moment, I am not planning a fully fleshed-out guided tour of VB.NET regex, although I certainly intend to add plenty of tasty material to this page over time. My pages are always in motion.

In the meantime, I don't want to leave you VB.NET coders out dry, so I have something special to get you started.


A VB.NET program that shows
how to perform common regex tasks

Whenever I start playing with the regex features of a new language, the thing I always miss the most is a complete working program that performs the most common regex tasks—and some not-so-common ones as well.

This is what I have for you in the following complete VB.NET regex program. It's taken from my page about the best regex trick ever, and it performs the six most common regex tasks. The first four tasks answer the most common questions we use regex for:

✽ Does the string match?
✽ How many matches are there?
✽ What is the first match?
✽ What are all the matches?

The last two tasks perform two other common regex tasks:

✽ Replace all matches
✽ Split the string

If you study this code, you'll have a terrific starting point to start tweaking and testing with your own expressions with VB.NET. Bear in mind that the code inspects values captured in Group 1, so you'll have to tweak… but you'll have a solid base to understand how to do basic things&and fairly advanced ones as well.

As you can imagine, I am not fluent in all of the ten or so languages showcased on the site. This means that although the sample code works, a VB.NET pro might look at the code and see a more idiomatic way of testing an empty value or iterating a structure. If some idiomatic improvements jump out at you, please shoot me a comment.

Please note that usually you will choose to perform only one of the six tasks in the code, so your own code will be much shorter.


Click to Show / Hide code
(The code compiles perfectly in VS2013, but no online demo supplied
because the VB.NET in ideone chokes on anonymous functions.)
Imports System
Imports System.Text.RegularExpressions
Imports System.Collections.Specialized

Module Module1
Sub Main()
Dim MyRegex As New Regex("{[^}]+}|""Tarzan\d+""|(Tarzan\d+)")
Dim Subject As String = "Jane"" ""Tarzan12"" Tarzan11@Tarzan22 {4 Tarzan34} "
Dim Group1Caps As StringCollection = New StringCollection()
Dim MatchResult As Match = MyRegex.Match(Subject)

' put Group 1 captures in a list
While MatchResult.Success
    If MatchResult.Groups(1).Value <> "" Then
        Group1Caps.Add(MatchResult.Groups(1).Value)
    End If
    MatchResult = MatchResult.NextMatch()
End While

'///////// The six main tasks we're likely to have ////////

'// Task 1: Is there a match?
Console.WriteLine("*** Is there a Match? ***")
If(Group1Caps.Count > 0) Then 
    Console.WriteLine("Yes")
Else 
    Console.WriteLine("No")
End If

'// Task 2: How many matches are there?
Console.WriteLine(vbCrLf & "*** Number of Matches ***")
Console.WriteLine(Group1Caps.Count)

'// Task 3: What is the first match?
Console.WriteLine(vbCrLf & "*** First Match ***")
If(Group1Caps.Count>0) Then Console.WriteLine(Group1Caps(0))


'// Task 4: What are all the matches?
Console.WriteLine(vbCrLf & "*** Matches ***")
If (Group1Caps.Count > 0) Then
   For Each match as String in Group1Caps
       Console.WriteLine(match)
   Next
End If   

'// Task 5: Replace the matches
Dim Replaced As String = myRegex.Replace(Subject, 
                     Function(m As Match)
                        If (m.Groups(1).Value = "") Then
                            Return m.Groups(0).Value
                        Else 
                            Return "Superman"
                        End If
                     End Function)
Console.WriteLine(vbCrLf & "*** Replacements ***")
Console.WriteLine(Replaced)

' Task 6: Split
' Start by replacing by something distinctive,
' as in Step 5. Then split.
Dim Splits As Array = Regex.Split(replaced,"Superman")
Console.WriteLine(vbCrLf & "*** Splits ***")
For Each Split as String in Splits
    Console.WriteLine(Split)
Next

Console.WriteLine(vbCrLf & "Press Any Key to Exit.")
Console.ReadKey()
End Sub
End Module

Read the explanation or jump to the article's Table of Contents





Smiles,

Rex

Buy me a coffee
Buy me a coffee