Menu

VB.NET TUTORIALS - VB.Net - Regular Expressions

VB.Net - Regular Expressions

ADVERTISEMENTS

The Regex Class

S.NMethods & Description
1Public Function IsMatch ( input As String ) As Boolean
Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
2Public Function IsMatch ( input As String, startat As Integer ) As Boolean
Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
3Public Shared Function IsMatch ( input As String, pattern As String ) As Boolean
Indicates whether the specified regular expression finds a match in the specified input string.
4Public Function Matches ( input As String ) As MatchCollection
Searches the specified input string for all occurrences of a regular expression.
5Public Function Replace ( input As String, replacement As String ) As String
In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
6Public Function Split ( input As String ) As String()
Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

ADVERTISEMENTS

Example 1

Imports System.Text.RegularExpressions
Module regexProg
   Sub showMatch(ByVal text As String, ByVal expr As String)
      Console.WriteLine("The Expression: " + expr)
      Dim mc As MatchCollection = Regex.Matches(text, expr)
      Dim m As Match
      For Each m In mc
          Console.WriteLine(m)
      Next m
   End Sub
   Sub Main()
      Dim str As String = "A Thousand Splendid Suns"
      Console.WriteLine("Matching words that start with 'S': ")
      showMatch(str, "\bS\S*")
      Console.ReadKey()
   End Sub
End Module

ADVERTISEMENTS

Example 2

Imports System.Text.RegularExpressions
Module regexProg
   Sub showMatch(ByVal text As String, ByVal expr As String)
      Console.WriteLine("The Expression: " + expr)
      Dim mc As MatchCollection = Regex.Matches(text, expr)
      Dim m As Match
      For Each m In mc
          Console.WriteLine(m)
      Next m
   End Sub
   Sub Main()
      Dim str As String = "make a maze and manage to measure it"
      Console.WriteLine("Matching words that start with 'm' and ends with 'e': ")
      showMatch(str, "\bm\S*e\b")
      Console.ReadKey()
   End Sub
End Module

Example 3

Imports System.Text.RegularExpressions
Module regexProg
   Sub Main()
      Dim input As String = "Hello    World   "
      Dim pattern As String = "\\s+"
      Dim replacement As String = " "
      Dim rgx As Regex = New Regex(pattern)
      Dim result As String = rgx.Replace(input, replacement)
      Console.WriteLine("Original String: {0}", input)
      Console.WriteLine("Replacement String: {0}", result)
      Console.ReadKey()
   End Sub
End Module