Regular expression for valid characters not working in Java

I have the following validation method for valid characters:

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

but if the test has a character -, it returns return false. Do I need to avoid -?

+5
source share
3 answers

Inside [... the ]character is -processed specially. (You use it for this special purpose at the beginning of your expression, where you have it a-z.)

You need to escape the character -

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

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

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

Some additional notes:

  • , + * .

  • String.matches , ^ $ .

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

A - , , .

- char, - char:

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

- char:

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

- char:

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

- , .

+1

All Articles