|
|
Title | Use regular expressions to replace text in the lines in a string in VB .NET |
Description | This example shows how to use regular expressions to replace text in the lines in a string in VB .NET. It uses the Regex class's Replace method to make the replacements. |
Keywords | regular expression, string, parsing, parse, replace |
Categories | Strings, Algorithms |
|
|
The program creates a Regex object, passing its constructor a regular expression pattern that will identify text to replace. It calls the object's Replace method, passing it the replacement pattern.
|
|
Private Sub btnGo_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnGo.Click
Try
Dim reg_exp As New Regex(txtPattern.Text)
lblResult.Text = reg_exp.Replace(txtInput.Text, _
txtReplacementPattern.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
|
|
The trick in this example lies in the search and replacement patterns. In this example, the search pattern is "(?m)^([^,]*), (.*)$". The pieces of this expression have the following meanings:
(?m) | This is an option directive that indicates a multi-line string. This makes the ^ and $ characters match the beginning and end of a line rather than the beginning and end of the string. |
^ | Match the beginning of a line. |
([^,]*) | Match any character other than comma any number of times. This part is enclosed in parentheses so it forms the first match group. |
, | Match a comma followed by a space. |
(.*) | Match any character any number of times. This part is enclosed in parentheses so it forms the second match group. |
$ | Match the end of the line. |
The replacement pattern is "$2 $1". This says to replace the stuff that was matched with the second match group, a space, and then the first match group.
This example takes this text:
Archer, Ann
Baker, Bob
Carter, Cindy
Deevers, Dan
And converts it into this:
Ann Archer
Bob Baker
Cindy Carter
Dan Deevers
|
|
|
|
|
|