1

I have a regex challenge for you (I need you help)

I'm trying to make a regex that finds "bbb" only if "aaa" is not present between the beginning of the string and the "bbb" word.

So I built the following expression: ^(?!.*(aaa)).*?(bbb)

It works but I noticed that "bbb" is not found when "aaa" is located after "bbb"... I need the expression to find "bbb" even if "aaa" is located between "bbb" and the end of the string.

So:

Must find "bbb" in:

"ddd bbb eee"
"bbb fff aaa"

Must not find "bbb" in:

"aaa bbb eee ddd" 
"aaa ccc bbb"

Ps: See this link (select Java) http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyEwsSBlJlY2lwZRiAgIDii-WPCgw/index.html to test the regex. I simplified the test strings for my case but just so you know, in real life those strings will be actual various sentences.

Thank you

EDIT:

Awwhh man! I always forget something in my regex questions! Loll

I forgot to mention that "bbb" needs to be replaced (replaceAll) by another word (ie: "zzz"). So the result of the expression needs to be a modified string and not a boolean.

So we should have these results:

"ddd bbb eee" => "ddd zzz eee"
"bbb fff aaa" => "zzz fff aaa"
"bbb ggg bbb" => "zzz ggg zzz"
"aaa bbb eee ddd" => "aaa bbb eee ddd"
"aaa ccc bbb" => "aaa ccc bbb"
"fff aaa eee bbb jjj bbb" => "fff aaa eee bbb jjj bbb"

Sorry I could not update the test link from my mobile.

Don Madrino
  • 147
  • 1
  • 11

1 Answers1

0

It's almost correct!!

Jus a small correction: String pattern = "^(?!.*(aaa).*?(bbb))";

public static void main(String[] args)
    {
        String[] lines =  {"ddd bbb eee",
                           "bbb fff aaa",
                           "aaa bbb eee ddd",
                           "aaa ccc bbb"};

        String pattern = "^(?!.*(aaa).*?(bbb))";

        Pattern p = Pattern.compile(pattern);


        for (String line: lines)
        {
            Matcher matcher = p.matcher(line);
            System.out.println(matcher.find());
        }
    }

O/p:

True
True
False
False

Hope this works..