Vic Mac
Vic Mac

Reputation: 33

Matching string between first and last parentheses

I need to pick up all texts between the first and last parentheses but am having a hard time with regex.

What I have is this so far and I'm stuck and don't know hot to proceed further.

/(\w+)\((.*?)\)\s/g)

But it stops at the first ")" that it sees.

Sample:

(me)

(mine)

((me) and (you))

Desired output is

me

mine

(me) and (you)

Upvotes: 3

Views: 4637

Answers (4)

brian d foy
brian d foy

Reputation: 132840

Here's a non-regex solution. Since you want the absolute first and last instances of fixed substrings, index and rindex find the right positions that you can feed to substr:

#!/usr/bin/perl
use v5.10;

while( <DATA> ) {
    chomp;

    my $start = 1 +  index $_, '(';
    my $end   =     rindex $_, ')';
    my $s = substr $_, $start, ($end - $start);

    say "Read: $_";
    say "Extracted: $s";
    }


__END__
(me)
(mine)
((me) and (you))

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

Since you want to capture all text inside parenthesis, you shouldn't use non-greedy quantifier. You can use this regex which uses lookarounds and greedy version .* which captures all text in between ( and ).

(?<=\().*(?=\))

Demo

EDIT: Another alternative solution

Another way to extract same data can be done using following regex which doesn't have any look ahead/behind which is not supported by some regex flavors and might be useful in those situations.

^\((.*)\)$

Here ^\( matches the starting bracket and then (.*) consumes any text in a exhaustive manner and places in first grouping pattern and only stops at last occurrence of ) before end of line.

Demo without lookaround

Upvotes: 1

sergiotarxz
sergiotarxz

Reputation: 540

Your code is almost correct, it would worked only if you would not add the ? in the regex, for example: (I have also removed a couple of things)

/\w+\((.*)\)/

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38512

A non-regex way with chop() and reverse()

$string='((me) and (you))';
chop($string);
$string = reverse($string);
chop($string); 
$string = reverse($string); 
print $string;

Output:

(me) and (you)

DEMO: http://tpcg.io/MhaLed

Upvotes: 0

Related Questions