Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleUse regular expressions to replace text in the lines in a string in VB .NET
DescriptionThis 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.
Keywordsregular expression, string, parsing, parse, replace
CategoriesStrings, 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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated