Detect if a String contains Special Characters

There are many ways to detect if a String contains Special Characters. In this code snippet, I will show a quick way to detect special characters using Regex.

C#

static void Main(string[] args)
{
string str = "Th!s $tri^g c@n$ist $pecial ch@rs";
Match match = Regex.Match(str, "[^a-z0-9]",
RegexOptions.IgnoreCase);
while (match.Success)
{
string key = match.Value;
Console.Write(key);
match = match.NextMatch();
}
Console.ReadLine();
}

VB. NET

Shared Sub Main(ByVal args() As String)
Dim str As String = "Th!s $tri^g c@n$ist $pecial ch@rs"
Dim match As Match = Regex.Match(str, "[^a-z0-9]", _
RegexOptions.IgnoreCase)
Do While match.Success
Dim key As String = match.Value
Console.Write(key)
match = match.NextMatch()
Loop
Console.ReadLine()
End Sub

Regex.Match searches the input string for the first occurrence of the regular expression specified. The Success property of the Match object tells us whether the regular expression pattern has been found in the input string. If yes, then print the first match and retrieve subsequent matches by repeatedly calling the Match.NextMatch method.

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

belleparas said...

extremely excellent! your blog article is really educational, interesting and very helpful as well. i'll be back to check new posts from you.

www.n8fan.net

jeegnesh said...

please add Special characterin in it