Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for including alphanumeric and special characters

Tags:

regex

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?

like image 969
Suryateja Kosaraju Avatar asked Jan 31 '13 23:01

Suryateja Kosaraju


People also ask

How do I add special characters to a regex pattern?

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).

How do I allow only special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.

What does \+ mean in regex?

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.

What is Alnum in regex?

The Alphanumericals are a combination of alphabetical [a-zA-Z] and numerical [0-9] characters, 62 characters.


1 Answers

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.

like image 91
Mark Byers Avatar answered Sep 20 '22 17:09

Mark Byers