简体   繁体   中英

Regex for alphanumeric and special characters

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?

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.

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\\/]+$";
                                    ^              ^   ^

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM