Reputation: 13975
As the title says: I want the input to be one or more symbols that is not in the union of letters, numbers and white space. So basically any of ~!@#, etc
. I have
"^(?=.*[[^0-9][^\w]])(?=\\S+$)$"
I know I could negate the appropriate set, but I don't know how to create my super set to start with. Would the following do?
"^(?=.*[(_A-Za-z0-9-\\+)])(?=\\S+$)$"
Upvotes: 4
Views: 394
Reputation: 15010
To match a string of one or more non letter, non number or non white space you with a regex you could use:
^(?:[^\w\s]|_)+$
You have to include the _
separately because the character class \w includes the _
. And the \w
character class is equivalent to [a-zA-Z_0-9]
reference link
Upvotes: 1
Reputation: 129517
Maybe you're looking for \p{Punct}
, which matches any of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
.
String re = "\\p{Punct}+";
Upvotes: 4
Reputation: 22692
I would just use a Character object to keep it simple.
Something like this:
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();
}
This would be even more straightforward:
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();
}
Upvotes: 0
Reputation: 17319
The class:
[^\w\s]
This will match any non-alphanumeric/non-whitespace character.
Java String
:
String regex = "[^\\w\\s]";
Upvotes: 3