Regular expressions are about finding and changing patterns. One of the most common that I always find is the need to reformat a “proper name”. It seems that every conversion program that I get involved in requires the re-ordering of the name. Regular expressions offer something called a backreference that can help with this. Basically, these patterns sets allow a quick way of finding the same string pattern again.
For an example, let’s assume that we have an inbound text string that has my name as “Robbins, Thom”. Unfortunately, when this string is updated it needs to be in the proper name format of “Thom Robbins”. Using a regular expression with a backreference, the following code can be used to switch these values.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim importname As String = "Robbins, Thom"
Dim regexp As New Regex("(\w+),\s(\w+)")
Dim updatename = regexp.Replace(importname, "$2 $1")
The above example matches two words separated by a comma and a space then reverses the order of the words. The Replace statement uses the $N notation to reference the Nth group of parenthesis.
Note: When you want to refer to the entire text string use the $0