Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

$b may not follow $a immediately, there may be something between them.

e.g. $a is 'foo', $b is 'bar', then:
'fooabc' should match
'fooabcdefg' should match
'abcd' should not match
'foobar' should not match
'fooabcbar' should not match
'abcbar' should not match
'fooabcbarefg' should not match

  • Comment on How do I match a expression start with $a and not contain $b after $a

Replies are listed 'Best First'.
Re: How do I match a expression start with $a and not contain $b after $a
by strat (Canon) on Jan 28, 2002 at 20:58 UTC
    This isn't an answer to your question, it's just a warning about better not using $a and $b except with sort because it can cause some funny problems:
    #!/opt/gnu/bin/perl -w use strict; $a = 40; # error because of use strict? no $b = $a; # error again ? no
    This code will not fail although neiter $a nor $b is declared despite of use strict.

    Best regards,
    perl -e "$_=*F=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

Re: How do I match a expression start with $a and not contain $b after $a
by Juerd (Abbot) on Jan 28, 2002 at 18:38 UTC
    /$a(?!.*$b)/

    I will have to kill those who comment on my usage of the dot star :)
      At the risk of death, you need a /s modifier if you want the intermediate junk to be able to include returns.

      Also you should be using \Q and \E escapes.

      /\Q$a\E(?!.*\Q$b\E)/s
      (The mistake of using $a and $b for normal use was the fault of the questioner, and not you.)
      That regex will match "foobarfoo" if $a = "foo" and $b = "bar", but it shouldn't.

      See this node.

      -Anomo
Re: How do I match a expression start with $a and not contain $b after $a
by Anonymous Monk on Jan 29, 2002 at 06:19 UTC
    It's easier to split up the task and use two regexes:     /$a/ && !/$a.*?$b/s; If you still very much want to have it in one regex you can use     /^(?>.*?$a)(?!.*?$b)/s; but that not compatible with perl 5.004 or earlier. (You can rewrite it to be compatible with perl 5.004, but I'll leave that as an exercise for you. Hint: look in the perlre manpage.)

    -Anomo
      I just noticed that it's not totally clear whether 'xfoobar' should match or not with $a = 'foo' and $b = 'bar'.

      -Anomo