Regular expression to check for special characters in a string

Today, I had to create a filter in which I detect if a text contains special characters. The goal of this was to ensure that the text being captured in a text field only contains letters and numbers.  To do this, I used regular expressions as this is one of the easiest ways to do this type of validations. Please find below my solution:

// Flag to detect special characters
bool Special_Characters_Found = false;

// String variable
string Text = "[This text contains speci@l characters]";

// Regular expression to check for special characters
var Contains_Special_Characters = new Regex("^[a-zA-Z0-9 ]*$");

/*
* Call: "IsMatch()" method to do the actual check.
* If true, special characters were found. Otherwise, the
* string does not contain any special characters
*/
if (Contains_Special_Characters.IsMatch(Text))
{
   Special_Characters_Found = true;
}
else
{
   Special_Characters_Found= false;
}

The result in this scenario would be True, as our string variable has three special characters:

  1.  [
  2.  @
  3.  ]

To use this code, just change Text variable and set the actual text you want to validate.

Let me know any questions!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s