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

> and I need to find the first occurrence of "+" that is not enclosed within parenthesis, i.e. the one before "5", how would I do that with a regular expression ?

depends what you mean with "finding"!

If it's just the position you need, a simple technique I like is to replace all inner paren-pairs till you get a "cleaned" string and then to try finding whatever it needs.

This demonstrates the intermediate results:

DB<172> $s=$s0 => "1*((2+3)*((3+4)+5))*(6+7)+8" DB<173> print "$s\n" while $s =~ s# \( [^()]* \) # '.' x length($&) +#gex 1*(.....*(.....+5))*.....+8 1*(.....*.........)*.....+8 1*.................*.....+8 DB<174> index $s, '+' => 25

Cheers Rolf

( addicted to the Perl Programming Language)

Replies are listed 'Best First'.
Re^2: Regex: first match that is not enclosed in parenthesis
by monkprentice (Novice) on Jun 30, 2013 at 13:53 UTC

    Finding in my case means to return the prefix and postfix substrings.

    I also thought of this. This way one could just find the substring before and after the retrieved position.
    Good Idea.

      Something like this:

      use strict; use warnings; my $input = "1*(2+3)*(3+4)+5*(6+7)"; my $level = 0; my $tab = "| "; my %action = ( '(' => sub { print "\n", $tab x ++$level, shift }, ')' => sub { print "\n", $tab x $level--, shift }, '+' => sub { print "This one>>>" unless $level; print +shift }, 'default' => sub { print shift }, ); ( $action{$_} // $action{'default'} )->($_) for $input =~ /./g;

      The additional effort is only worthwhile if you have ambitions beyond your initial question.

      Sounds like what you really need is a lexer.

      hdb regularly posts such solutions based on dispatch tables, worth searching for...

      HTH! =)

      Cheers Rolf

      ( addicted to the Perl Programming Language)