8

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

0

3 Answers 3

16

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-]*");
    
Sign up to request clarification or add additional context in comments.

1 Comment

Since we have a-zA-Z0-9_ as part of the character class, wouldn't it simplify things to use \w instead?, i.e. "[\\w,.;:'\\s-]*"
2

You can put the - at the start of the character group so that it is not interpreted as a character range.

Comments

2

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]+$")) 
                    ^

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.