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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

jeegnesh said...

please add Special characterin in it