If, as your example suggests, you do not need arbitrarily nested parens, the following will work:

my $str = "1*(2+3)*(3+4)+5*(6+7)"; $str =~ /(?: \( .+? \) | [^+()] )+ (\+ .*)/x; say "Match: $1";

Outputs:

Match: +5*(6+7)

However, if you need to handle a string where a + sign immediately follows a closing paren, such as ((3+4)+2), you can use recursive regexps:

$str = "1*(2+3)*(7+(3+4)+2)+5*(6+7)"; $str =~ /( \( (?: [^()]++ | (?1) )* \) | [^+()] )+ (\+ .*)/x; say "Match: $2";

Outputs:

Match: +5*(6+7)

Update: Here's a more descriptive version of that last regexp:

/( # Capture group 1 \( # Opening paren (?: # Non-capture group [^()]++ # Match non-brackets, no backtracking | (?1) # Recurse to group 1. (?R) works, too. )* # Zero or more times \) # Closing paren | [^+()] # Anything outside of parens not a + or paren )+ # Not *, assuming you only want addition, not # +positive integers at beginning of string (\+ .*) # Plus sign, and remainder of string /x;

In reply to Re: Regex: first match that is not enclosed in parenthesis by rjt
in thread Regex: first match that is not enclosed in parenthesis by monkprentice

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.