Example
The following code example illustrates the use of a regular expression to check whether a string has the correct format to represent a currency value. Note the use of enclosing ^ and $ tokens to indicate that the entire string, not just a substring, must match the regular expression.
Imports System.Text.RegularExpressions
Public Class Demo
Public Shared Sub Main()
Dim rx As New Regex("^-?\d+(\.\d{2})?$")
Dim values() As String = {"-42", "19.99", "0.001", "100 USD"}
For Each value As String In values
If rx.IsMatch(value) Then
Console.WriteLine("{0} is a currency value.", value)
Else
Console.WriteLine("{0} is not a currency value.", value)
End If
Next
End Sub
End Class
The following code example illustrates the use of a regular expression to check for repeated occurrences of words within a string. Note the use of the (?<word>) construct to name a group and the use of the (\k<word>) construct to refer to that group later in the expression.
Imports System.Text.RegularExpressions
Public Class Demo
Public Shared Sub Main()
' Define a regular expression for repeated words.
Dim rx As New Regex("\b(?<word>\w+)\s+(\k<word>)\b", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
' Define a test string.
Dim text As String = "The the quick brown fox fox jumped over the lazy dog dog."
' Find matches.
Dim matches As MatchCollection = rx.Matches(text)
Dim word As String
Dim index As Integer
' Report the number of matches found.
Console.WriteLine("{0} matches found.", matches.Count)
' Report on each match.
For Each found As Match In matches
word = found.Groups("word").Value
index = found.Index;
Console.WriteLine("{0} repeated at position {1}", word, index)
Next End Sub
End Class