Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make an arbitrary Perl regex wholly non-capturing? (Answer: You Can't)
    primarykey
    data
    text
    <p>How can I remove capturing from arbitrarily nested sub-groups in a a Perl regex string? I'd like to nest any regex into an enveloping expression that captures the sub-regex as a whole entity as well as statically known subsequent groups. Do I need to transform the regex string manually into using all non-capturing <code>(?:)</code> groups (and hope I don't mess up), or is there a Perl regex or library mechanism that provides this?</p> <pre><code># How do I 'flatten' $regex to protect $2 and $3? # Searching 'ABCfooDE' for 'foo' OK, but '((B|(C))fo(o)?(?:D|d)?)', etc., breaks. # I.E., how would I turn it effectively into '(?:(?:B|(?:C))fo(?:o)?(?:D|d)?)'? sub check { my($line, $regex) = @_; if ($line =~ /(^.*)($regex)(.*$)/) { print "&lt;", $1, "&gt;&lt;", $2, "&gt;&lt;", $3, "&gt;\n"; } } </code></pre> <p><strong>Addendum:</strong> I am vaguely aware of <code>$&amp;</code>, <code>$&#96;</code>, and <code>$'</code> and have been advised to avoid them if possible, and I don't have access to <code>${^PREMATCH}</code>, <code>${^MATCH}</code> and <code>${^POSTMATCH}</code> in my Perl 5.8 environment. The example above can be partitioned into 2/3 chunks using methods like these, and more complex real cases could manually iterate this, but I think I'd like a general solution if possible.</p> <p><strong>Accepted Answer:</strong> What I wish existed and surprisingly (to me at least) does not, is an encapsulating group that makes its contents opaque, such that subsequent positional backreferences see the contents as a single entity and names references are de-scoped. <a href="https://stackoverflow.com/questions/3552850/how-do-i-make-an-arbitrary-perl-regex-wholly-non-capturing-answer-you-cant/3553154#3553154"><strong>gbacon</strong></a> has a potentially useful workaround for Perl 5.10+, and <a href="https://stackoverflow.com/questions/3552850/how-do-i-make-an-arbitrary-perl-regex-wholly-non-capturing-answer-you-cant/3552965#3552965"><strong>FM</strong></a> shows a manual iterative mechanism for any version that can accomplish the same effect in specific cases, but <a href="https://stackoverflow.com/questions/3552850/how-do-i-make-an-arbitrary-perl-regex-wholly-non-capturing-answer-you-cant/3553154#3553154"><strong>j_random_hacker</strong></a> calls it that there is no real language mechanism to encapsulate subexpressions.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload