Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Regex: first match that is not enclosed in parenthesis

by james2vegas (Chaplain)
on Jun 30, 2013 at 10:17 UTC ( #1041566=note: print w/replies, xml ) Need Help??

in reply to Regex: first match that is not enclosed in parenthesis

You might want to split the string using Text::Balanced's extract_multiple function and then apply a map to extract your data (this code extracts the first '+' and replaces it with a '-'):
use strict; use warnings; use List::Util qw/first/; use Text::Balanced qw/extract_multiple extract_bracketed/; my $text = "1*(2+3)*(3+4)+5*(6+7)+42"; my @results = extract_multiple( $text, [ { Bracketed => sub { extract_bracketed( $_[0], '()' ) } }, { PlusOperator => qr{[+]} }, { MultiplyOperator => qr{[*]} }, { Number => qr{\d+(?:\.\d+)?} }, ] ); my $operator = first { ref($_) eq 'PlusOperator' } @results; # $operator holds '+' my $plus; my $new_string = join( '', map { if ( !$plus && ref $_ eq 'PlusOperator' ) { $plus = 1; '-' } else { $$_ } } @results ); print "$new_string\n";
or the answer is 'no', regexes that parse data like that are never going to be elegant.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1041566]
[Corion]: marto: Great! The German Perl Workshop was a success even though things looked dire before, and I'm now back at home with two days off work still to go ;)
[Corion]: I hope things have settled down a bit for you and the boys are alright?!

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2017-06-29 08:01 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (655 votes). Check out past polls.