Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Perl function to turn a string into a regexp to use that string as pattern?

Tags:

string

regex

perl

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

like image 618
philant Avatar asked Oct 15 '08 12:10

philant


People also ask

How do I match a string in regex in Perl?

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.

Which function performs Perl style pattern matching on a string?

PHP's Regexp PERL Compatible Functions The preg_match_all() function matches all occurrences of pattern in string.

Is Perl used for pattern matching?

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.

Can regex be a string?

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.


2 Answers

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
like image 52
Adam Bellaire Avatar answered Oct 02 '22 11:10

Adam Bellaire


I think you are looking for quotemeta

like image 38
Leon Timmermans Avatar answered Oct 02 '22 10:10

Leon Timmermans