in reply to How regexes fail.
A lexer returns tokens, and tokens are rather simple. So simple that parsing them requires no backtracking. This makes it very easy to not use regexps.
But it also your task possible (but not simple) with regexps too. Take Perl single-quoted strings:
becomessub squote { my $s_pos = pos; my $match = / \G ' (?> (?: \\. | [^\\'] )* ) ' /xsgc; my $e_pos = pos; if ($match) { $_[0] = substr($_, $s_pos, $e_pos-$s_pos); return 1; } else { pos = $s_pos; return 0; } }
sub squote { my $s_pos = pos; RETRY: { local our $at_eof = ...; local our $need_more = 0; my $match = / \G (?: \z (?{ $need_more = !$at_eof }) )? ' (?> (?: \\ (?: \z (?{ $need_more = !$at_eof }) )? . | [^\\'] )* ) (?: \z (?{ $need_more = !$at_eof }) )? ' /xsgc; if ($need_more) { ... pos = $s_pos; redo RETRY; } my $e_pos = pos; if ($match) { $_[0] = substr($_, $s_pos, $e_pos-$s_pos); return 1; } else { pos = $s_pos; return 0; } } }
By the way, you asked
"How can I tell if a regular expression is matching but fails merely because it ran out of data?"
but you should also be asking
"How can I tell if a regular expression succeeded merely because it ran out of data?"
Take an identifier, for example. If $_ contains 'abc', it'll return a match, but it'll return the wrong match if the next character is 'd'.
sub ident { my $s_pos = pos; my $match = / \G [a-zA-Z_] [a-zA-Z0-9_]* /xsgc; my $e_pos = pos; if ($match) { $_[0] = substr($_, $s_pos, $e_pos-$s_pos); return 1; } else { pos = $s_pos; return 0; } }
becomes
sub ident { my $s_pos = pos; RETRY: { local our $at_eof = ...; local our $need_more = 0; my $match = / \G (?: \z (?{ $need_more = !$at_eof }) )? [a-zA-Z_] (?> [a-zA-Z0-9_]* ) (?: (?= . ) | (?{ $need_more = !$at_eof }) ) /xsgc; if ($need_more) { ... pos = $s_pos; redo RETRY; } my $e_pos = pos; if ($match) { $_[0] = substr($_, $s_pos, $e_pos-$s_pos); return 1; } else { pos = $s_pos; return 0; } } }
Update: Simple optimization.
|
|---|