Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a string into a regular expression that matches itself in Perl?

Tags:

regex

perl

How can I convert a string to a regular expression that matches itself in Perl?

I have a set of strings like these:

Enter your selection:
Enter Code (Navigate, Abandon, Copy, Exit, ?):

and I want to convert them to regular expressions sop I can match something else against them. In most cases the string is the same as the regular expression, but not in the second example above because the ( and ? have meaning in regular expressions. So that second string needs to be become an expression like:

Enter Code \(Navigate, Abandon, Copy, Exit, \?\):

I don't need the matching to be too strict, so something like this would be fine:

Enter Code .Navigate, Abandon, Copy, Exit, ..:

My current thinking is that I could use something like:

s/[\?\(\)]/./g;

but I don't really know what characters will be in the list of strings and if I miss a special char then I might never notice the program is not behaving as expected. And I feel that there should exist a general solution.

Thanks.

like image 620
Anon Gordon Avatar asked Nov 28 '22 02:11

Anon Gordon


2 Answers

As Brad Gilbert commented use quotemeta:

my $regex = qr/^\Q$string\E$/;

or

my $quoted = quotemeta $string;
my $regex2 = qr/^$quoted$/;
like image 51
daotoad Avatar answered Dec 21 '22 12:12

daotoad


There is a function for that quotemeta.

quotemeta EXPR
Returns the value of EXPR with all non-"word" characters backslashed. (That is, all characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings.

If EXPR is omitted, uses $_.

like image 40
Brad Gilbert Avatar answered Dec 21 '22 10:12

Brad Gilbert