Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern including all special characters

Tags:

java

regex

I want to write a simple regular expression to check if in given string exist any special character. My regex works but I don't know why it also includes all numbers, so when I put some number it returns an error.

My code:

//pattern to find if there is any special character in string Pattern regex = Pattern.compile("[$&+,:;=?@#|'<>.-^*()%!]"); //matcher to find if there is any special character in string Matcher matcher = regex.matcher(searchQuery.getSearchFor());  if(matcher.find()) {     errors.rejectValue("searchFor", "wrong_pattern.SearchQuery.searchForSpecialCharacters","Special characters are not allowed!"); } 
like image 685
Piotr Sagalara Avatar asked Aug 05 '13 12:08

Piotr Sagalara


People also ask

How do you include special characters in regular expressions?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \.

What does ?! Mean in regex?

It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment). Follow this answer to receive notifications.

How do I escape a character in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.


1 Answers

Please don't do that... little Unicode BABY ANGELs like this one 👼 are dying! ◕◡◕ (← these are not images) (nor is the arrow!)

And you are killing 20 years of DOS :-) (the last smiley is called WHITE SMILING FACE... Now it's at 263A... But in ancient times it was ALT-1)

and his friend

BLACK SMILING FACE... Now it's at 263B... But in ancient times it was ALT-2

Try a negative match:

Pattern regex = Pattern.compile("[^A-Za-z0-9]"); 

(this will ok only A-Z "standard" letters and "standard" 0-9 digits.)

like image 177
xanatos Avatar answered Oct 03 '22 02:10

xanatos