简体   繁体   中英

Regular expression to check allowed characters not working in Java

I have the following method to check allowed characters:

private boolean checkIfAllCharsAreValid(String test) {
    boolean valid = false;
    if (test.matches("^[a-zA-Z0-9,.;:-_'\\s]+$")) {
        valid = true;
    }
    return valid;
}

but if test has the character - in it the match return false. Do i have to escape the - ?

Inside [ ... ] the - symbol is treated specially. (You use it yourself in this special purpose in the beginning of your expression where you have az .)

You need to escape the - character

[a-zA-Z0-9,.;:\-_'\s]
              ^

or put it last (or first) in the [...] expression like

[a-zA-Z0-9,.;:_'\s-]
                   ^

Some further notes:

  • Technically speaking all characters are valid in the empty string, so I would change from + to * in your expression.

  • String.matches checks the full string, so the ^ and $ are redundant.

  • Your entire method could be wirtten as

     return test.matches("[a-zA-Z0-9,.;:_'\\\\s-]*"); 

A - in a character class surrounded on both sides is a regex meta character to denote range.

To list a literal - in a char class you escape the - in the char class:

if (test.matches("^[a-zA-Z0-9,.;:\\-_'\\s]+$")) 
                                 ^^^ 

or place the - at the end of char class:

if (test.matches("^[a-zA-Z0-9,.;:_'\\s-]+$")) 
                                      ^

or place the - at the beginning of char class:

if (test.matches("^[-a-zA-Z0-9,.;:_'\\s]+$")) 
                    ^

您可以将-放在字符组的开头,以便它不会被解释为字符范围。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM