1

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).

4
  • Sorry, for the little advert (i only use the tool myself, i don't work for them) but you can try the software regexpal mentions "regexbuddy" which allows you to even export a function to use in Java. Commented May 7, 2011 at 19:50
  • Are you sure that you have shown us the right expression and input? That expression matches that input on regexpal.com for me and when I run "ADC".matches("A.*?C"). Commented May 7, 2011 at 19:54
  • 1
    Why should DEAGHHF match A.?C|C.?A|D.?C|C.?D|A.?F|F.?A The regexp says that the string should be of length 2 or 3. The string that you have is way longer than that, so you can only get a partial match. Commented May 7, 2011 at 20:05
  • There were asteriks misssing, it should match with "A.*?F" Commented May 7, 2011 at 20:08

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah works for me too. For testing RegEx for Java I recommend regexplanet.com/simple/index.html - got that from SO myself. Really great implementation with quite some useful bells and whistles (especially the "get regex as java string" is awesome!)
Sorry the asteriks didn't show up, fixed first post again. Thanks
Matcher was what I was looking for, correct, thank you. And your explanation of the regex was helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.