tags:

views:

44

answers:

3

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?

+1  A: 

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 %"

David Dorward
+5  A: 

^[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.

Amarghosh
Oh, sometime you just make very stupid mistakes. I though the + or * sign was before not after. I just didn't see it when I looked at other examples either... Thank you.
Peter Eriksson
A: 

You just check for one of the [%/] characters to appear, not the possibility of having both.

Try [%/]? (or +, *, depending what you want)

ApoY2k