Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for alphanumeric and special characters

Tags:

c#

regex

vb.net

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?

like image 369
dotNetNewbie Avatar asked Dec 01 '22 06:12

dotNetNewbie


2 Answers

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.

like image 75
Ry- Avatar answered Dec 05 '22 17:12

Ry-


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\\/]+$";
                                    ^              ^   ^
like image 39
Bergi Avatar answered Dec 05 '22 17:12

Bergi