|Title||Use regular expressions to replace characters within parts of a string surrounded by quotes in Visual Basic .NET|
|Description||This example shows how to use regular expressions to replace characters within parts of a string surrounded by quotes in Visual Basic .NET.|
|Keywords||regular expression, regex, regexp, replace, VB .NET|
|Categories||VB.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, _
' Add the text before the next match.
If match.Index > next_unmatched Then
result &= input.Substring(next_unmatched, _
match.Index - next_unmatched)
' 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
' Add the rest of the string.
If input.Length > next_unmatched Then
result &= input.Substring(next_unmatched)
' Display the result.
txtResult.Text = result