Proper Case Demo using Regular Expressions

This demo illustrates using a Replace delegate to customize the regular expression Replace() method. Enter some text into the textbox below, and then click the "Convert to Proper Case" button. This will display the text you entered in "proper case," which is where each first letter of each word is capitalized.

Enter some text that you want to convert to proper case:

Source Code
<script language="VB" runat="server">
Sub btnSubmit_Click(sender as Object, e as EventArgs)
    Dim myDelegate As New MatchEvaluator( AddressOf MatchHandler )
    Dim sb As New System.Text.Stringbuilder()
    Dim bodyOfText As String = txtBody.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)
    lblResults.Text =  "<b>Original Text:</b><br />" & bodyOfText & _
                       "<p><b>Proper Case:</b><br />" & newString
End Sub

Private Function MatchHandler( ByVal m As Match ) As String
    Return m.Groups(1).Value.ToUpper() & m.Groups(2).Value
End Function

  <form runat="server">
    Enter some text that you want to convert to proper case:<br />
    <asp:TextBox runat="server" id="txtBody" TextMode="MultiLine" Rows="15" Columns="40" />
    <asp:Button runat="server" Text="Convert to Proper Case" OnClick="btnSubmit_Click" />
    <asp:label id="lblResults" runat="server" />

[Return to the article]