in reply to How to find where regex did not match across the line

I want to know exactly where the pattern did not match the given line in the loop

well, everywhere.

Or to phrase it differently, the regex didn't match anywhere, so every position in the string is a position where the match failed.

So, the question is, what do you want to tell the user? That the line contained ABC but not a whitespace after it? then you need to run a second regex. Or you could presumably match a regex that always matches, and then use that to see how far you got, but it's not so easy.

Update: One can do something like

use strict; use warnings; $_ = 'stuffABC Xmorestuff'; if (/((A(?:B(?:C(?:\s+(?:X(?:Y(?:Z)?)?)?)?)?)?))/) { print "Searched for 'ABC\\s+XYZ' but only found $1"; }

But that won't give good output in the most general case. Probably the most intuitive output is searching for the longest partial match:

use strict; use warnings; $_ = 'stuAffABC XmoresABtuff'; my $longest = ''; while (/((A(?:B(?:C(?:\s+(?:X(?:Y(?:Z)?)?)?)?)?)?))/g) { $longest = $1 if length($1) > length($longest); } print "Searched for 'ABC\\s+XYZ' but only found '$longest'\n"; __END__ Searched for 'ABC\s+XYZ' but only found 'ABC X'

Note that Perl 6 has a special regex feature for constructing such regexes (<* regex that can match partially>, though nobody has implemented that yet).

Second update: I realized that it might help to explain why there isn't a good way to determine why a regex failed to match in the general case.

One must understand that a successful regex match typically is typically preceeded by quite a number of "small" failures. For example if you do a match like 'abc' =~ /.*c/, then a naive regex engine would first try to match .* against the entire string, then determines that the 'c' can't match, then backtrack, that is make .* one less character, and then the 'c' can match too. (Perl actually keeps track of the length of the regex that remains, so it's a bit smarter, but there are other cases where it can't be smart).

So if the regex .*c fails to match a string, it has tried every possible starting position within that string, and all the attempts have been unsuccessful. Which attempt should be reported as "the" unsuccessful attempt? There's no good answer to that question in the general case.

Also a regex engine would need to keep around lots of data in memory to report why stuff failed, which isn't a good idea for successful matches.

Note that if you run a program with perl -Mre=debug yourprogram.pl you'll get some information why a regex match failed, but it's not a format that would make it useful to a normal user (who isn't a programmer).

Replies are listed 'Best First'.
Re^2: How to find where regex did not match across the line
by Anonymous Monk on Mar 13, 2012 at 04:40 UTC

    Hello,
    Thanks for elaborating. Gives me a different dimension to code!