Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Sorry couldn't think of a short snappy title to this problem.

Is there a way of using the grouping re capability in Perl without (implicity) increasing the variable count. That is I want to match and replace some stuff without ending up referring to $largenumber.

For example, given the substitution

s/(some|stuff)(more|stuff).*?(what I really want here)/$3/;

I would like to use $1 rather than $3 cause the first two groupings are really there just to anchor the pattern. I don't need them in the substitution.

A more extreme case is

$htmltag="(<[^>]+>)"; s/<td>$htmltag{99}(.*?)<\/td>/$100/;

I really am just interested in the (.*?) grouping, the other groupings are just there to make the repetition count work out right. Am I stuck with $100 or is there a way to group expressions without using parentheses?

Thanks,

M

Code tags added by GrandFather

Replies are listed 'Best First'.
Re: Grouping regular expressions
by friedo (Prior) on Sep 20, 2006 at 22:59 UTC

    You can use non-capturing groups:

    s/(?:some|stuff)(?:more|stuff).*?(what I really want here)/$1/;
Re: Grouping regular expressions
by GrandFather (Saint) on Sep 20, 2006 at 23:00 UTC

    I assume your immediate problem is that you want to group without capturing. Use the non-capturing group brackets:

    /(?:some|stuff)(?:more|stuff).../

    I note in your second example however that you may be intending to use regexen for processing HTML. As noted many times before, life is too short to reinvent that particular wheel - there are far too many subtle edge cases and you will get bit! Much better to use tools such as HTML::TreeBuilder or, if you are dealing with XHTML, XML::Twig.


    DWIM is Perl's answer to Gödel