I am having a little trouble understanding regular expressions. My question is: How do you know when it is a good time to use parenthesis in a pattern. I know that if I would like to store a value in memory than I could use them. In an exercise in the Learning Perl book it says: Make a pattern that matches only lines containing either the word fred or wilma, followed by some whitespace, and then the word flintstone. So it should match the string: I am fred flintstone(with one or more spaces or tabs between the names.) Well my idea of what the code should look like is this:
/\bfred|wilma\s+flintstone\b/
However, the book lists the code like this:
/\b(fred|wilma)\s+flintstone\b/
I do not understand why the parenthesis are needed here. But I do see that if I take them away it causes problems because if I type just flintstone at the prompt it will not match. However, if I leave the parenthesis in the pattern as the book does than flintstone will match... could someone please clarify this for me..

-Warren E Bullock III wbullock@twcny.rr.com

Edit kudra, 2002-06-08 Changed title, added code tags


In reply to Parenthesis usage in Regular Expressions by WarrenBullockIII

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.