http://qs1969.pair.com?node_id=565081


in reply to Strange result from "abbbbbc" =~ /(b)*?(b*?)c/

To explain further how your regular expression is problematic, in case you find it helpful:

What you're saying with "/(b)*?/" is that you want to match "b" and store it in $1, and do this zero or more times, but no more times than necessary. As ikegami notes, what you may mean is "/(b*?)/, which says that you want to match "b" zero or more times, but no more than necessary, and store the collection of characters matched in $1.

The difference is that the first might be trying to store any number of different single instances of "b" in $1, all of which are matched, it may even store no instances of "b" in $1. It may have trouble deciding which single instance to put in $1. It looks like back in 5.6.1 the regular expression engine gets really confused by this, as well it might.

In 5.8.x versions it looks like it decides to take the first instance, which is "no" occurances of "b".

Adendum for those who know the RE engine: I know this is not how the RE engine works on the string, it's meant as an explanation of why the expression is ambiguous, rather than how the RE engine works (which the general reader of an RE shouldn't have to know, IMO). The 5.6.1 engine has a bug here, but it is a lot to ask of the little engine that could.

Replies are listed 'Best First'.
Re^2: Strange result from "abbbbbc" =~ /(b)*?(b*?)c/
by mcovic (Initiate) on Aug 01, 2006 at 22:04 UTC
    Thank you all for you help. It just confirmed my suspicion that this was indeed a bug. The Version I have is 5.8.0. As for those who tried to explain why this regular expression is problematic, this regular expression is fine and was specifically designed to test this very specific thing. And there is a nice use of (X)* (where X is any other expression) because it gives you the last occurence of pattern X (at least in my version of perl).

      It's not evident that that is a "nice use if (X)*" given that different versions of Perl handle the rather bogus expression differently. The same result can be achieved using zero width assertions:

      "babbbbbcbbbcx" =~ /(?:b)(?!.*b)(..)/; print ">$1<\n"; # >cx<

      Update s/\Q(?!(?=.*b))\E/(?!.*b)/. Thanks to ikegami for pointing out the redundancy.


      DWIM is Perl's answer to Gödel
      How much different it would have been to have this background information in the original post, where it would have helped us figure out how to be of help, instead of puting our work into gueses of what was needed.

      With this statement showing up afterward like this, with the "yes, yes just as I thought" tone, I'm feeling less like I've been of help, and more like I've been mislead for someone's amusement.

      Oh well, win some, lose some.