Re: Variable inside regular expression
- From: "Paul Lalli" <mritty@xxxxxxxxx>
- Date: 30 Jun 2006 09:17:02 -0700
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
.
- References:
- Variable inside regular expression
- From: mattwoolnough
- Variable inside regular expression
- Prev by Date: RE: Crypt::GPG won't decrypt file...rewrote it to use system, but only partially works
- Next by Date: Re: the FOR Loop in the English Language
- Previous by thread: Re: Variable inside regular expression
- Next by thread: Perl Binary to Perl Code
- Index(es):
Relevant Pages
|