Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Pattern Matcher COMMA [duplicate]

Tags:

java

regex

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?

like image 232
KernelCurry Avatar asked Jun 03 '26 04:06

KernelCurry


1 Answers

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 ]).

like image 172
Sergey Kalinichenko Avatar answered Jun 05 '26 17:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!