3

I am trying to use a pattern check against a string, and for some reason it is saying that strings that shouldn't match, do..

Code:

private static final Pattern VALID_TOKEN = Pattern.compile("^[a-zA-Z0-9\\{\\}\\[\\].+-/=><\\\\*]*$");
System.out.println(VALID_TOKEN.matcher(token).matches());

Examples:

"123" = true
"1,3" = true // Should NOT BE TRUE
"123*123" = true
"123*^123" = false

All of the above examples are correct except "1,3" the pattern should not include a COMMA. Does anyone have any ideas?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
KernelCurry
  • 1,297
  • 1
  • 13
  • 31

1 Answers1

2

You need to escape the dash in

+-/

Otherwise, it is interpreted as a range from '+' to '/' - a range that includes '+', ',', '-'. '.', and '/'.

private static final Pattern VALID_TOKEN = Pattern.compile("^[a-zA-Z0-9\\{\\}\\[\\].+\\-/=><\\\\*]*$");
//                              Here ------------------------------------------------^^

Alternatively, you can move the dash to the end of the character class (i.e. put it before the closing ]).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523