Dim myString As String = RegEx.Replace( "a true taste of the temperature", "t.*?e\b", "a" )
After the replace operation has occurred, the value of myString will be "a a a of a a" and it's fairly obvious what happened. Every time the regular expression parser found a match within the string it replaced it with the letter "a". That's all nice and easy if all you need to do is a straight replace, but what about if you need to implement some sort of business logic into the check or you need to "touch" the sub-matches in some way and re-build the replaced string.
mc = re.Matches( bodyOfText )
Dim m As Match
For Each m In mc
sb.AppendFormat("{0}{1}", m.Groups(1).Value.ToUpper(), m.Groups(2).Value)
Next
That would work fine if your string contained only word characters, but, what if it looked like this: ~~~ This %%% is ### a chunk of text. After the replacement operation you would end up with the following string meaning that all non-word characters that didn't participate in the matches were dropped: ThisIsAChunkOfText. There are ways around it, mostly by building bigger, more complex patterns and doing more string building inside the match collection iteration.
Sub Page_Load(sender as Object, e as EventArgs)
Dim myDelegate As New MatchEvaluator( AddressOf MatchHandler )
Dim sb As New System.Text.Stringbuilder()
Dim bodyOfText As String = _
"~~~ This %%% is ### a chunk of text."
Dim pattern As String = "\b(\w)(\w+)?\b"
Dim re As New Regex( _
pattern, RegexOptions.Multiline Or _
RegexOptions.IgnoreCase _
)
Dim newString As String = re.Replace(bodyOfText, myDelegate)
Response.Write( bodyOfText & "<hr>" & newString )
End Sub
Private Function MatchHandler( ByVal m As Match ) As String
Return m.Groups(1).Value.ToUpper() & m.Groups(2).Value
End Function
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)