2 ms·
I don't think they really give you a structural way to use regexes; more of a procedural way, where you can embed regexes within explicit loops that iterate ove
by _delirium 14y ago
I don't think they really give you a structural way to use regexes; more of a procedural way, where you can embed regexes within explicit loops that iterate over lines, matching and updating state-variables as you go. Unlike regexes, which are declarative and abstract away the details of the match algorithm and its internal match-progress variables, you are explicitly maintaining the match state there. I find myself writing manual-FSM code like if($scanning_for_new_record) { /.../; }. And even that only really works if you can do a one-pass match, without needing to backtrack across line boundaries.
It's inelegant enough that I sometimes do a two-step process instead: 1) transform the input so that whatever view I want of it maps to a line-oriented format; and then 2) process the result in the standard Unix line-oriented fashion.
- Roboprog 14y agoSeems like it shouldn't be too hard to write a little function (perl, python, whatever) to act as a "visitor" to hold this state, then just pass it little closures (maybe a hash/map?) to evaluate the regexs and pass the match into a code block? Something like (perl): &visit_matches( { ' +' => sub { $x += length( $1); }, '#+' => sub { print $1, ' at ' $y, ',', $x'; $x += length( $1); }, '\n' => sub { $y++; } }); (not an exact match to the pseudo-awk, but enough to get the idea)