Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to check allowed characters not working in Java

Tags:

java

regex

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 -?

like image 465
Nicola Peluchetti Avatar asked Nov 09 '11 10:11

Nicola Peluchetti


1 Answers

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

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-]*");
    
like image 69
aioobe Avatar answered Oct 19 '22 13:10

aioobe