Search code examples
regexperlregex-lookaroundsnon-greedy

Keep the TRUE non-greedy match using Perl regex


From the following word "tacacatac", I want to match "cat". It seems like the regex c.*?t should give me this, but I guess it starts with the first occurrence of "c" and then from there finds the next "t", and thus, matches "cacat".

Is there a way to (perhaps using negative lookahead) start looking from the c just before the final t?

-----edit----- I need an option that will work if you replace the letters with strings

Thanks.


Solution

  • try this:

    my $str = "the cat in the cat in the hat";
    if ($str =~ /(cat(?:(?!cat).)*hat)/) {
        print $1, "\n";
    }