W3docs

Regex pattern including all special characters

To create a regular expression that includes all special characters, you can use the following pattern:

To create a regular expression that includes all special characters, you can use the following pattern:


[\!@#%^&*()_+\-=\[\]{}|;':",./<>?~\`]

This regular expression will match any single special character in the list.

For example, you can use this regular expression to test if a string contains any special characters:


import java.util.regex.Matcher;
import java.util.regex.Pattern;

String input = "Hello World!";
Pattern pattern = Pattern.compile("[\\!@#%^&*()_+\\-=\\[\\]{}|;':\",./<>?~\\`]");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
    System.out.println("Input contains special characters.");
} else {
    System.out.println("Input does not contain special characters.");
}

This will output "Input contains special characters."

Note that characters like [, ], -, and \ have special meanings in regular expressions and must be escaped with a backslash (\) to match them literally.

Also, be aware that this regular expression only includes a specific set of ASCII special characters. If you need to match all possible punctuation characters, consider using the \p{Punct} Unicode character property, which matches any Unicode punctuation character.