Regex for alphanumeric and special characters

26,986

Solution 1

The [] in the middle need to be escaped*:

\[\]

You also probably want to anchor the start of the string with a ^.


* Probably just the ] but I like to do both for balance.

Solution 2

When defining a character class, you will need to escape the closing bracket ] within, just like "^", "-" and the escaping sequence \ itself, which you have done correctly:

string pattern = @"[a-zA-Z0-9@#$%&*+\-_(),+':;?.,![\]\s\\/]+$";
                                    ^              ^   ^

Solution 3

Some of those characters need to be escaped (*, +, etc). The easiest way is to simply escape them all:

string pattern = @"[a-zA-Z0-9\@\#\$\%\&\*\(\)\-\_\+\]\[\'\;\:\?\.\,\!]+$";
Share:
26,986
dotNetNewbie
Author by

dotNetNewbie

Updated on May 18, 2020

Comments

  • dotNetNewbie
    dotNetNewbie about 4 years

    I need to define a regular expression that accepts Alphanumeric and the following special characters: @#$%&*()-_+][';:?.,!

    I've come up with:

    string pattern = @"[a-zA-Z0-9@#$%&*+\-_(),+':;?.,![]\s\\/]+$";
    

    But this doesn't seem to be working. Can someone please let me know what is missing?