Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex not working - why?

match.matches() returns false. This is odd, because if I take this regex and test String to rubular.com, is shows two matches. What am I doing wrong?

    Pattern regex = Pattern.compile("FTW(((?!ODP).)+)ODP");
    Matcher match = regex.matcher("ZZZMMMJJJOOFTWZMJZMJODPZZZMMMJJJOOOFTWMZJOMZJOMZJOODPZZZMMMJJJOO");

    if (match.matches()) {
        System.out.println("match found");
    }
    else {
        System.out.println("match not found");
    }
like image 393
Nick Heiner Avatar asked Dec 19 '25 02:12

Nick Heiner


2 Answers

Matcher.matches returns whether or not the whole region matches the pattern.

Try using find instead. (Certainly with your example, this works fine.)

like image 135
Jon Skeet Avatar answered Dec 20 '25 18:12

Jon Skeet


The Matcher.matches() method tries to match the entire string to the pattern. Change your pattern to:

".*FTW(((?!ODP).)+)ODP.*"
like image 27
paxdiablo Avatar answered Dec 20 '25 19:12

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!