Tuesday 30 October 2012

Remove Special Characters and Space From String Using Regex


Remove Special Characters and Space From String Using Regex

Hi I will be discussing now how to remove special characters and space from a given string.. In this project i will be using two multiline textboxes and a button to demonstrate the functionality:

Design Part:


    <div>
    <br />
    <br />
        <asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" Height="200px" Width="300px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Trim String" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:TextBox ID="TextBox2" TextMode="MultiLine" runat="server" Height="200px" Width="300px"></asp:TextBox>
    </div>


Code Behind:

Include the Namespace-

using System.Text.RegularExpressions;

Then use the following codes:

    public static string RemoveSpecialCharacters(string str)
    {
        // Strips all special characters and spaces from a string.
        return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        string str=TextBox1.Text;
        TextBox2.Text=RemoveSpecialCharacters(str);
    }


On Button Click you will get the trimmed string in the second textbox..

Hope It helps.. Vishal   

2 comments:

Thank You for Your Comments. We will get back to you soon.

back to top