hadley/stringr — pull request #29 by jonclayden (2013-06-07 14:22:23+00:00)
Title: Getting str_match to work with Perl regular expressions

I primarily use Perl-style regular expressions, and the lack of the ability to capture grouped substrings in R can be a pain. This patch to `str_match` allows it to work with Perl regular expressions, albeit not via `regexec`, since, of course, it doesn't support them. My strategy is to

- find the start and length of each match with `regexpr`, and extract the matching substring; then
- for each group, use `sub` to replace the substring with the content of the group in question.

This route seems pretty reliable, since it uses the regular expression engine itself to do the work, rather than depending on any hacks.

The old approach to calculating the number of groups was also quite brittle (it would be fooled by `"[^(]"`, for example), so I also take a more robust approach to that.

I hope this is helpful.