I have requirement to allow alphanumeric and certain other characters for a field. I am using this regular expression:
"^[a-zA-Z0-9!@#$&()-`.+,/\"]*$".
The allowed special characters are! @ # $ & ( ) - ‘ . / + , “
But when I test the pattern with a string "test_for_extended_alphanumeric" , the string passes the test. I don't have "_"
allowed in the pattern. What am I doing wrong?
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.
Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.
The Alphanumericals are a combination of alphabetical [a-zA-Z] and numerical [0-9] characters, 62 characters.
You need to escape the hyphen:
"^[a-zA-Z0-9!@#$&()\\-`.+,/\"]*$"
If you don't escape it then it means a range of characters, like a-z
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With