将Perl变量转换为regex

将Perl变量转换为regex,regex,perl,hash,Regex,Perl,Hash,给你 my %id_to_name = ( 51803 => 'Jim bob and associates', ); while (my ($key, $value) = each %id_to_name) { $regex = qr/^.*?$value.*?$/; $value = $regex; 我基本上想将$value匹配到: a bunch of random text blah blah 'Jim bob and associates' blah

给你

my %id_to_name = (
    51803 => 'Jim bob and associates',
);

while (my ($key, $value) = each %id_to_name) {
    $regex = qr/^.*?$value.*?$/;
    $value = $regex;
我基本上想将
$value
匹配到:

a bunch of random text blah blah 'Jim bob and associates' blah blah.
因为前后的文字太多,我似乎找不到匹配的


我正在尝试
qr/
,但它似乎不起作用。有什么建议吗?

看起来你不需要正则表达式来做这个。。。该函数将允许您检查字符串是否包含子字符串

print $value if index($input, $value) >= 0;
仅供参考,正则表达式解决方案将是:

print $value if $input =~ m/\Q$value\E/;

如果需要修饰符(如
i
用于不区分大小写的匹配),可以使用它<代码>\Q…。\E与Perl 5.18.2类似。

my %id_to_name = (
    51803  =>  'Jim bob and associates',
            );

while (my ($key, $value) = each %id_to_name) {
    $regex = qr/^.*?$value.*?$/;
    print "$regex\n";
    $test="a bunch of random text blah blah 'Jim bob and associates' blah blah.";
    print "match" if $test =~/$value/;
}
印刷品:

(?^:^.*?Jim bob and associates.*?$)
match

如注释中所述,前导和尾随的
*?
是毫无意义的

也许是
=~
而不是
=
?到底什么“似乎不起作用”?您希望您的代码做什么?您可能需要
my$regex=qr/\Q$value/
。前导和尾随的
*?
中根本没有点。