John Strickler
John Strickler

Reputation: 25421

Regex works in other engines but not Java Pattern/Matcher

I can't figure out why this regex doesn't work, I've tested it in php and other regex engines where it works fine and matches ",AA,".

Pattern p = Pattern.compile("(^|,)AA(,|$)");

Matcher m = p.matcher("A,B,AA,C,D");

//assigns as false  
boolean matches = m.matches();

Side note: I have a split/array binary search method for doing an IN_SET / NOT_IN_SET search against the string. This is just an example I need to get working before implementing regex as another comparing option.

Upvotes: 1

Views: 133

Answers (2)

Qwerky
Qwerky

Reputation: 18445

Matcher matches the entire region against the pattern. Use find().

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170227

matches() validates the entire string. You want to use find() instead.

From the API:

matches()

Attempts to match the entire region against the pattern.

-- http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#matches()

and:

find()

Attempts to find the next subsequence of the input sequence that matches the pattern.

-- http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#find()

Upvotes: 4

Related Questions