I want to use regular expressions (Perl compatible) to be able to find a pattern surrounded by two other patterns, but not include the strings matching the surrounding patterns in the match.
For example, I want to be able to find occurrences of strings like:
Foo Bar Baz
But only have the match include the middle part:
Bar
I know this is possible, but I can’t remember how to do it.
In the general case, you probably can’t. The simplest approach is to match everything and use backreferences to capture the portion of interest:
This isn’t the same as not including the surrounding text in the match though. That probably doesn’t matter if all you want to do is extract ‘Bar’ but would matter if you’re matching against the same string multiple times and need to continue from where the previous match left off.
Look-around will work in some cases. Tomalak’s suggestion:
only works for fixed width look-behind (at least in Perl). As of Perl 5.10, the
\Kassertion can be used to effectively provide variable width look-behind:which should be capable of doing what you asked for in all cases, but would require that you’re implementing this in Perl 5.10.
While it would be convenient, there’s no equivalent of
\Kfor ending the matched text, so you have to use a look-ahead.