You can construct character classes (and negated character classes) based on backreferences on the fly with the (??{ .... }) regexp subexpression. Here's an example:

use strict; use warnings; my $string = "that bab"; print "Match: $1 => $2" if $string =~ m/(that).+((??{ '[' . $1 . ']' }))/; __OUTPUT__ Match: that => a

The above example matches 'that', and then uses the characters in 'that' as characters in a character class constructed within the (??{...}) subexpression. Since 'a' was one of the characters within 'that', it is matched, and captured into $2.

This gets a little tripped up if the first character held in the backreference is also a character class metacharacter, such as ^ (which would construct a negated character class), or if there is an embedded hyphen, which would attempt to construct a range, as in 'a-z'. And be careful with embedded backslashes because within a character class they might look like '\d' (the combination used for matching any digit character. So this technique is somewhat sensitive to the type of data you're looking at, but with reasonably sanitary strings it can be effective.


Dave


In reply to Re: Matching Character Patterns With Backreferences by davido
in thread Matching Character Patterns With Backreferences by Anonymous Monk

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.