Your regex has several problems. First, your regex requires at least two instances of foo(num) to match - it can't match just one because the next expressions in the pattern are non-optional.

Also, your regex uses .+? in ways that allow the pattern to defeat your requirements. Consider this string - "foo(10)bar(10)", which I assume shouldn't match. But it will match /.+?\(\d+\)/. The reason is that .+? can match "foo(10)bar" and then the rest of the match can succeed on just "(10)". I fixed this by changing your .+? to [^\(]+ which means "any character except an open paren". You might be able to narrow that down further.

Finally, you didn't anchor your pattern which means that it is free to match anywhere in the string. I added \A to the front and \z to the end to force the regex to span the whole string.

Here's a replacement pattern that works, documented using the /x modifer that allows whitespace and comments:

/ \A # start at the beginning of the string [^\(]+ # match one or more non-( characters \(\d+\) # match a (number) expression ( # start the optional part : # a single, required colon [^\(]+ # match one or more non-( characters \(\d+\) # match a (number) expression )* # match this subexpression zero or more times \z # end at the end of the string /x;

-sam

UPDATE: My first attempt was bad news. Just goes to show you can never think too carefully about a regex!


In reply to Re: One or more of a pattern... by samtregar
in thread One or more of a pattern... by kiat

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.