gvalkov / python-oneliner

Module for practical Python one-liners
Other
37 stars 7 forks source link

Add support for regex matching #7

Open Lucretiel opened 6 years ago

Lucretiel commented 6 years ago

I was thinking of writing a pull request, but also wanted to gauge interest in a feature like this:

Currently, one of the shorthands provided by oneliner is to automatically split the input line on whitespace and provide the result to words or W. I was thinking it might be nice to add a feature for full regex matching. It would look like this:

pyl -n -r '^regex (group)$' -e <cmd>.

If -r or -R are present, it executes the regex for each input line. It then provides the shortcuts match/M, for the match object, as well as groups/G for the list of matched groups, and gdict/GD for the dict of named groups. Additionally, for named groups, I'd propose adding the matches directly as variables to the execution context, if they don't conflict with existing names like line. This would allow something like this:

pyl -n -r '(?P<date>\d{2}/\d{2}/\d{4})' -j -e '"The date is", date'

The difference between -r and -R is that one of them would cause execution to completely ignore lines that don't match the regex, whereas the other would cause match to be None in the event of failed matches.