Cote Mounyo
Cote Mounyo

Reputation: 13975

java regex for "any symbol" that's neither word nor number nor space

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

Answers (4)

Ro Yo Mi
Ro Yo Mi

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]|_)+$

enter image description here

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

arshajii
arshajii

Reputation: 129517

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

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

Upvotes: 4

jahroy
jahroy

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

Brian
Brian

Reputation: 17319

The class:

[^\w\s]

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

Java String:

String regex = "[^\\w\\s]";

Upvotes: 3

Related Questions