Ajay
Ajay

Reputation: 2078

Java Regex Fails to Find a match

This should return true, but instead returns false.

"ADC".matches("A.*?C")

I've tested it on a javascript regex tester : http://regexpal.com/

and it works, why doesn't it work in Java?

EDIT: Same with this:

System.out.println("DEAGHHF".matches("(A.*?C|C.*?A|D.*?C|C.*?D|A.*?F|F.*?A)"));

Returns false, regexpal returns true (aswhile as other javascript regex engines).

Upvotes: 1

Views: 1392

Answers (1)

aioobe
aioobe

Reputation: 420951

No, it returns true.

System.out.println("ADC".matches("A.*?C"));

prints true.

The regexpal.com implementation seems to be buggy (which is understandable since it is version 0.1.4). Try entering ABC repeatedly. Only every second ABC gets rejected. (At least when viewing it in my version of firefox.)

Regarding your edit:

A.?C|C.?A|D.?C|C.?D|A.?F|F.?A

is interpreted as

A.*?C   or
C.*?A   or
D.*?C   or
C.*?D   or
A.*?F   or
F.*?A

In other words

Something that starts with A and ends with C, or
Something that starts with C and ends with A, or
Something that starts with D and ends with C, or
....
Something that starts with F and ends with A,

Since "DEAGHHF" starts with D and ends with F, it won't match.

Perhaps you're looking for the Matcher.find method

Upvotes: 6

Related Questions