I have trouble using Perl grep() with a string that may contain chars that are interpreted as regular expressions quantifiers.
I got the following error when the grep pattern is "g++" because the '+' symbols are interpreted as quantifiers. Here is the output of for program that follows:
1..3
ok 1 - grep, pattern not found
ok 2 - grep, pattern found
Nested quantifiers in regex; marked by <-- HERE
in m/g++ <-- HERE / at escape_regexp_quantifier.pl line 8.
Is there a modifier I could use to indicate to grep that the quantifiers shall be ignored, or is there a function that would escape the quantifiers ?
#! /usr/bin/perl
sub test_grep($)
{
my $filter = shift;
my @output = ("-r-xr-xr-x 3 root bin 122260 Jan 23 2005 gcc",
"-r-xr-xr-x 4 root bin 124844 Jan 23 2005 g++");
return grep (!/$filter/, @output);
}
use Test::Simple tests => 2;
ok(test_grep("foo"), "grep, pattern not found");
ok(test_grep("gcc"), "grep, pattern found");
ok(test_grep("g++"), "grep, pattern found");
PS: in addition to the answer question above, I welcome any feedback on Perl usage in the above as I'm still learning. Thanks
Simple word matching In this statement, World is a regex and the // enclosing /World/ tells Perl to search a string for a match. The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match.
PHP's Regexp PERL Compatible Functions The preg_match_all() function matches all occurrences of pattern in string.
m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.
Regex examples. A simple example for a regular expression is a (literal) string. For example, the Hello World regex matches the "Hello World" string. . (dot) is another example for a regular expression.
The standard way is to use the \Q
escape indicator before your variable, to tell Perl not to parse the contents as a regular expression:
return grep (!/\Q$filter/, @output);
Altering that line in your code yields:
1..3 ok 1 - grep, pattern not found ok 2 - grep, pattern found ok 3 - grep, pattern found
I think you are looking for quotemeta
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With