Java regex for “any character”, that neither word, nor number, nor space

As the title says: I want the input to be one or more characters that are not a combination of letters, numbers, and spaces. So basically any of ~!@ #, etc I have

 "^(?=.*[[^0-9][^\w]])(?=\\S+$)$" 

I know that I can undo the corresponding set, but I don’t know how to create my own super set to start with it. Will there be the following?

 "^(?=.*[(_A-Za-z0-9-\\+)])(?=\\S+$)$" 
+4
source share
4 answers

Perhaps you are looking for \p{Punct} that matches any of the !"#$%&'()*+,-./:;<=> ?@ []^_`{|}~ .

 String re = "\\p{Punct}+"; 
+4
source

Grade:

 [^\w\s] 

This will match any character other than alphanumeric / non-whitespace.

Java String :

 String regex = "[^\\w\\s]"; 
+3
source

To match a string of one or more letters, not numeric or non-white spaces, with a regular expression that you could use:

^(?:[^\w\s]|_)+$

enter image description here

You must include _ separately, because the \ w character class includes _ . And the character class \w equivalent to [a-zA-Z_0-9] link link

+1
source

I would just use the Character object to make it simple.

Something like that:

 public String getSpecialSymbols(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { Character c = s.charAt(i); if (!c.isDigit() && !c.isWhitespace() && !c.isLetter()) { sb.append(c); } } return sb.toString(); } 

That would be even simpler:

 public String getSpecialSymbols(String s) { String special = " !@ #$%^&*()_+-=[]{}|'\";\\:/?.>,<~`"; for (int i = 0; i < s.length(); i++) { String c = s.substring(i, 1); if (special.contains(c)) { sb.append(c); } } return sb.toString(); } 
0
source

Source: https://habr.com/ru/post/1490610/


All Articles