Regex doesn't work in Java code, but on test site

I was working on some regex that should accept "P1" and "P2", but for sure only these two combinations. So, I tested on this site: http://www.regexr.com/ which led me to

\b(P1)\b|\b(P2)\b

      

The site just gets the right matches.

Obviously the same in my java code won't work:

if(commandParameter.matches("\b(P1)\b|\b(P2)\b")){
        return false;
    }

      

As commandParamter, I give either P1 or P2. It doesn't return false anyway. Do you have any ideas?

+3


source to share


1 answer


Note that matches will perform an exact match, not a partial match.

if(commandParameter.matches(".*\\bP[12]\\b.*")){
    return false;
}

      



For an exact match.

if(commandParameter.matches("P[12]")){
        return false;
    }

      

0


source







All Articles