Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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.


Comment on Re: Regex: first match that is not enclosed in parenthesis
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1041566]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2014-08-20 16:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (118 votes), past polls