Re: Variable inside regular expression



mattwoolnough@xxxxxxxxx wrote:
Im trying to get specific groups out of the unix group file. The list
of group names is contained in Group_list.txt, when I try and run this
code, I get no output. Is it possible to use variables inside regex?

Yes, it is. But that variable will be interpolated into the pattern
match *before* it is interpreted by the regular expression engine.
That means that if your variable contains any characters that are
"special" in regexps, they will have their "specialness", rather than
literally match themselves. For example:

my $title = "M*A*S*H";
$line = 'MHMDNSAF';
if ($line =~ /^$title/) { print "Match\n"; }

Does it surprise you to learn that this code does print "Match"? What
if I had changed that last line to:
if ($line =~ /^M*A*S*H/) { print "Match\n"; }
Now does it surprise you? The regexp engine found the beginning of the
string, 0 or more 'M' (one, to be precise), 0 or more 'A' (none), 0 or
more 'S' (none), and one H.

So how do you get around this? By automatically quoting any special
characters in your variables, by surrounding your variable with the
\Q...\E sequence. See perldoc perlre, and perldoc -f quotemeta:

if ($line =~ /^\Q$title\E/) { print "Match\n"; }

This produces no output, as expected.

Hope this helps,
Paul Lalli

.



Relevant Pages

  • Re: Rounder Characters in No Time Flat!
    ... >>>I think that's good advice for seasoned writers but not inexperienced ... >>>everything's a surprise, soon nothing's a surprise. ... The characters of Elmore Leonard constantly confound ...
    (misc.writing)
  • Re: Replace special characters
    ... I don't know a great deal about Unicode - just some things from mucking around with high-order special characters a few years ago. ... What you're saying is actually rooted in the regular expression engine, not the LCID - although it could come out to the same thing if a particular regex engine uses arbitrary OS APIs to classify characters. ...
    (microsoft.public.scripting.vbscript)
  • Re: Replace special characters
    ... by VBScript's regular expression engine. ... I don't know a great deal about Unicode - just some things from mucking ... around with high-order special characters a few years ago. ... saying is actually rooted in the regular expression engine, ...
    (microsoft.public.scripting.vbscript)
  • Re: brave new fiction.
    ... story (exactly 140 characters). ... By a writing contest that counts not even words but CHARACTERS? ... What did surprise me, though, was where they found his ...
    (rec.arts.sf.composition)
  • Re: Finally got around to seeing SAW 3 this weekend....
    ... I actually thought the 2nd was the best of the franchise. ... You thinkin the 2nd was the best doesnt surprise me. ... Lets just throw a bunch of characters in a house and kill them ... but the second's twist ending was even better. ...
    (rec.sport.pro-wrestling)