Reputation: 239
I have a problem with the % and / characters in Java regex. The following example will illustrate my issue:
Pattern pattern = Pattern.compile("^[a-z]*[/%]$");
Matcher m = pattern.matcher("a%/");
System.out.println(m.find());
It prints "false" when I expect it to be "true". The % and / sign shouldn't have to be escaped but even if I do it still dosn't work.
So my question is simply why?
Upvotes: 1
Views: 97
Reputation: 17831
You just check for one of the [%/]
characters to appear, not the possibility of having both.
Try [%/]?
(or +, *, depending what you want)
Upvotes: 0
Reputation: 59451
^[a-z]*[/%]$
matches zero or more lower case letters followed by one character which can be either /
or %
- to allow multiple characters, use
^[a-z]*[/%]+$
+
stands for one or more; use *
for zero or more.
If you didn't have $
at the end of the regex, it would have matched a%
in the stringa%/
.
$
matches end of line.
Upvotes: 5
Reputation: 943981
Your regular expression says "zero or more lower case letters then /
or %
then the end of the string".
The string matches until it gets a /
when it was looking for the end of the string.
You probably want to remove the square brackets to say "/
then %
"
Upvotes: 1