Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Expressions for all non alphanumeric symbols

Tags:

c#

regex

I am trying to make a regular expression for a string that has at least 1 non alphanumeric symbol in it

The code I am trying to use is

Regex symbolPattern = new Regex("?[!@#$%^&*()_-+=[{]};:<>|./?.]");

I'm trying to match only one of !@#$%^&*()_-+=[{]};:<>|./?. but it doesn't seem to be working.

like image 211
Kevin Avatar asked Jun 24 '10 21:06

Kevin


5 Answers

If you want to match non-alphanumeric symbols then just use \W|_.

Regex pattern = new Regex(@"\W|_"); 

This will match anything except 0-9 and a-z. Information on the \W character class and others available here (c# Regex Cheet Sheet).

  • https://www.mikesdotnetting.com/article/46/c-regular-expressions-cheat-sheet
like image 82
JaredPar Avatar answered Oct 03 '22 14:10

JaredPar


You could also avoid regular expressions if you want:

return s.Any(c => !char.IsLetterOrDigit(c)) 
like image 31
ChaosPandion Avatar answered Oct 03 '22 14:10

ChaosPandion


Can you check for the opposite condition?

Match match = Regex.Match(@"^([a-zA-Z0-9]+)$");
if (!match.Success) {
    // it's alphanumeric
} else {
    // it has one of those characters in it.
}
like image 24
Jubal Avatar answered Oct 03 '22 12:10

Jubal


I didn't get your entire question, but this regex will match those strings that contains at least one non alphanumeric character. That includes whitespace (couldn't see that in your list though)

[^\w]+
like image 22
simendsjo Avatar answered Oct 03 '22 14:10

simendsjo


Your regex just needs little tweaking. The hyphen is used to form ranges like A-Z, so if you want to match a literal hyphen, you either have to escape it with a backslash or move it to the end of the list. You also need to escape the square brackets because they're the delimiters for character class. Then get rid of that question mark at the beginning and you're in business.

Regex symbolPattern = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

If you only want to match ASCII punctuation characters, this is probably the simplest way. \W matches whitespace and control characters in addition to punctuation, and it matches them from the entire Unicode range, not just ASCII.

You seem to be missing a few characters, though: the backslash, apostrophe and quotation mark. Adding those gives you:

@"[!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]"

Finally, it's a good idea to always use C#'s verbatim string literals (@"...") for regexes; it saves you a lot of hassle with backslashes. Quotation marks are escaped by doubling them.

like image 44
Alan Moore Avatar answered Oct 03 '22 12:10

Alan Moore