If there are no restrictions such as "must start with a letter" or "must contain at least one letter" (your question doesn't specify any), and assuming that by "white spaces" you mean a space, but not tabs, newlines, etc., then the expression would just be:

Pattern.compile("^[\\$#\\+{}:\\?\\.,~@\"a-zA-Z0-9 ]+$");

Note that this regular expression allows things such as only a single space, or a user name identical to another one except for the number of trailing spaces, etc. if you want to be a little more restrictive and enforce starting with a letter or number (for example), you could do:

Pattern.compile("^[a-zA-Z0-9][\\$#\\+{}:\\?\\.,~@\"a-zA-Z0-9 ]+$");
Answer from hair raisin on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › guide to escaping characters in java regexps
Guide to Escaping Characters in Java RegExps | Baeldung
July 22, 2024 - According to the Java regular ... characters as is instead of interpreting them with their special meanings, we need to escape them....
Top answer
1 of 3
3

If there are no restrictions such as "must start with a letter" or "must contain at least one letter" (your question doesn't specify any), and assuming that by "white spaces" you mean a space, but not tabs, newlines, etc., then the expression would just be:

Pattern.compile("^[\\$#\\+{}:\\?\\.,~@\"a-zA-Z0-9 ]+$");

Note that this regular expression allows things such as only a single space, or a user name identical to another one except for the number of trailing spaces, etc. if you want to be a little more restrictive and enforce starting with a letter or number (for example), you could do:

Pattern.compile("^[a-zA-Z0-9][\\$#\\+{}:\\?\\.,~@\"a-zA-Z0-9 ]+$");
2 of 3
1

Use this pattern which allows characters that are not on your blacked listed characters.

"[^^;\\-()<>|='%_]+"

The first ^ means NOT any of the following characters. Until you clarify if the $ is good or bad, I'm treating it as a good character.

Code sample:

public static void main(String[] args) throws Exception {
    List<String> userNames = new ArrayList() {{
        add("Name1$");          // Good
        add("Name1# Name2");    // Good
        add("Name1 Name2");     // Good
        add("Name Name2");      // Good
        add("Name1 Name");      // Good
        add("UserName$");       // Good
        add("UserName^");       // Bad
        add("UserName;");       // Bad
        add("User-Name");       // Bad
        add("User_Name");       // Bad
    }};
    Pattern pattern = Pattern.compile("[^^;\\-()<>|='%_]+");

    for (String userName : userNames) {
        if (pattern.matcher(userName).matches()) {
            System.out.println("Good Username");
        } else {
            System.out.println("Bad Username");
        }
    }
}

Results:

Good Username
Good Username
Good Username
Good Username
Good Username
Good Username
Bad Username
Bad Username
Bad Username
Bad Username
Discussions

java - Regex pattern including all special characters - Stack Overflow
0 How can I check if the last char ... [JavaScript] -1 vba regEx multiple patterns for different columns · 0 Regular Expression - character class for special characters ... Comedy film about a honeymooning couple in a camper. She collects rocks. A later scene has them jettisoning the rocks to get up a hill · Does UK GDPR Article 82 allow a UK resident ... More on stackoverflow.com
🌐 stackoverflow.com
java - Need a regular expression for field which should allow special characters, alphanumeric characters, and spaces - Stack Overflow
You simply need to escape the special characters. Try: ... Sign up to request clarification or add additional context in comments. ... +1 You're essentially right. My only comment is that, depending on the Regex engine being used, certain special characters don't need to be escaped. More on stackoverflow.com
🌐 stackoverflow.com
java - Regular expression include and exclude special characters - Stack Overflow
I'm finding a regular expression which adheres below rules. Allowed Characters Alphabet : a-z / A-Z Numbers : 0-9 Special Characters : ~ @ # $ ^ & * ( ) - _ + = [ ] { } | \ , . ? : (spaces More on stackoverflow.com
🌐 stackoverflow.com
java - Android: Accept all special characters in regex - Stack Overflow
I'm validating the Edittext with regex by allowing particular characters in that i need to allow all the special characters to enter in edit text. for allowing alpha and numbers im using the code More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 65585767 › regex-java-allow-number-letters-special-char-some
Regex Java allow number, letters, special char (some) - Stack Overflow
You need to escape the special characters with a slash. I think only '.' should be escaped and - and _ don't need escaping. ... Perhaps - and _ have an issue with CASE_INSENSITIVE, consider Pattern.UNICODE_CASE.
🌐
Delft Stack
delftstack.com › home › howto › java › java regex special charcters
How to Handle Regex Special Characters in Java | Delft Stack
February 14, 2024 - In the exploration of various methods involving regex special characters in Java, several techniques were applied to create precise search patterns within strings. The first method involved escaping special characters using backslashes, as demonstrated by the regex red\\, blue. This approach ensures the exact matching of the literal sequence red, blue. Next, character classes were employed with the regex [rgb], allowing for the matching of any single character among r, g, or b.
🌐
Regular-Expressions.info
regular-expressions.info › characters.html
Regex Tutorial: Literal Characters and Special Characters
If you forget to escape a special character where its use is not allowed, such as in +1, then you will get an error message. There are a few exceptions, though. BRE-style flavors, for example, *1 as a literal regex. Most regular expression flavors treat the brace { as a literal character, unless it is part of a repetition operator like a{1,3}. So you generally do not need to escape it with a backslash, though you can do so if you want. But there are a few exceptions. Java requires literal opening braces to be escaped.
Find elsewhere
🌐
ServiceNow Community
servicenow.com › community › developer-forum › regex-validation-to-allow-specific-special-characters-and › m-p › 2550236
Regex validation to allow specific special characters and disallow the rest of special characters
May 2, 2023 - Go to Solution. ... Hi @Aditya Banka2 , I trust you are doing great. To allow the specific special characters "." , "-" , and "_" while disallowing the rest of the special characters, you can modify the regex pattern in the validator on the catalog item variable.
🌐
Medium
medium.com › sina-ahmadi › java-regex-6e4d073aab85
Java RegEx. special characters issue in Java split… | by Sina | My journey as a software developer | Medium
June 20, 2018 - What happenes is if you put any special characters (like ‘+’, ‘*’ or ‘?’) as a splitter for string, Java considers that character to be a special character (not an actual character where you’re doing an split on), so the split is not done properly (or not done at all).
🌐
javathinking
javathinking.com › blog › regular-expression-for-excluding-special-characters
How to Create a Regular Expression to Exclude Special Characters (e.g., <>,%$) and Allow Accented Letters, Digits & Specific Chars for Input Validation in Java Web Apps — javathinking.com
Add your custom allowed special characters (e.g., _, -, ., ) to the character class. Note: Hyphens (-) must be placed at the start/end of the class or escaped to avoid being interpreted as a range: ... Use + to require one or more allowed characters ...
🌐
3SL
threesl.com › home › blog › special characters in regexes and how to escape them
Special characters in regexes and how to escape them
February 3, 2023 - If you want to match 1+2=3, you need to use a backslash (\) to escape the + as this character has a special meaning (Match one or more of the previous). To match the 1+2=3 as one string you would need to use the regex 1\+2=3
🌐
NTU Singapore
www3.ntu.edu.sg › home › ehchua › programming › howto › Regexe.html
Regular Expression (Regex) Tutorial
You can also write \d+, where \d is known as a meta-character that matches any digit (same as [0-9]). There are more than one ways to write a regex! Take note that many programming languages (C, Java, JavaScript, Python) use backslash \ as the prefix for escape sequences (e.g., \n for newline), and you need to write "\\d+" instead.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › regex › Pattern.html
Pattern (Java Platform SE 8 )
1 week ago - When this flag is specified then the input string that specifies the pattern is treated as a sequence of literal characters. Metacharacters or escape sequences in the input sequence will be given no special meaning.