Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this Regex, matches incorrect characters?

I need to match these characters. This quote is from an API documentation (external to our company):

Valid characters: 0-9 A-Z a-z & # - . , ( ) / : ; ' @ "

I used this Regex to match characters:

^[0-9a-z&#-\.,()/:;'""@]*$

However, this wrongly matches characters like %, $, and many other characters. What's wrong?

You can test this regular expression online using http://regexhero.net/tester/, and this regular expression is meant to work in both .NET and JavaScript.

like image 499
Saeed Neamati Avatar asked Dec 03 '22 06:12

Saeed Neamati


2 Answers

You are not escaping the dash -, which is a reserved character. If you add replace the dash with \- then the regex no longer matches those characters between # and \

like image 139
andyb Avatar answered Dec 19 '22 18:12

andyb


Move the literal - to the front of the character set:

^[-0-9a-z&#\.,()/:;'""@]*$

otherwise it is taken as specifying a range like when you use it in 0-9.

like image 38
Mat Avatar answered Dec 19 '22 19:12

Mat