Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regular expressions how do I find a pattern surrounded by two other patterns without including the surrounding strings?

Tags:

regex

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.

like image 781
LJ. Avatar asked Dec 04 '22 16:12

LJ.


1 Answers

Parentheses define the groupings.

"Foo (Bar) Baz"

Example

~> cat test.pl
$a = "The Foo Bar Baz was lass";

$a =~ m/Foo (Bar) Baz/;

print $1,"\n";
~> perl test.pl
Bar
like image 200
Vinko Vrsalovic Avatar answered Apr 17 '23 19:04

Vinko Vrsalovic