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 characters within parts of a string surrounded by quotes in Visual Basic .NET
DescriptionThis example shows how to use regular expressions to replace characters within parts of a string surrounded by quotes in Visual Basic .NET.
Keywordsregular expression, regex, regexp, replace, VB .NET
CategoriesVB.NET, Algorithms, Strings
 
This example looks for parts of a string surrounded by double quotes and replaces occurrences of / with ? within those parts. The rest of the string also contains / so you can see that the code doesn't replace those instances.

When you click the Replace button, the program uses Regex.Matches to get a collection of matches for the pattern "[^"]*". This pattern matches a quote, followed by any number of non-quotes, followed by a quote.

For each match, the code adds the part of the input string between this match and the previous one and then the matched text with the appropriate replacement. After it has processed each match, the code adds any text remaining in the input string.

 
Private Sub btnReplace_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnReplace.Click
    Dim input As String = txtInput.Text
    Dim result As String = ""
    Dim next_unmatched As Integer = 0

    For Each match As Match In Regex.Matches(input, _
        txtPattern.Text)
        ' Add the text before the next match.
        If match.Index > next_unmatched Then
            result &= input.Substring(next_unmatched, _
                match.Index - next_unmatched)
        End If

        ' Add the matched text.
        result &= match.Value.Replace("/", "?")
        ' Debug.WriteLine("[" & match.Value & "]")

        ' Set next_unmatched to the index 
        ' of the last character in this match.
        next_unmatched = match.Index + match.Length
    Next match

    ' Add the rest of the string.
    If input.Length > next_unmatched Then
        result &= input.Substring(next_unmatched)
    End If

    ' Display the result.
    txtResult.Text = result
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated