Perl的正则表达式 - 动态正则表达式
问题描述:
简单的问题(我希望)Perl的正则表达式 - 动态正则表达式
特殊字符我有一个包含符号的动态字符串:,/,等 基本上它是在我的Apache的错误文件中的日志行URL字符串?
我解析我的日志文件,我想看看如果URL的某些实例中的行存在:
URL线搜索:“http://www.foo.com?blah”
问号把我抛弃了,就像任何specia l正则表达式中的字符。我想下面:
my $test1 = 'my?test';
my $test2 = 'this is a my?test blah test';
if ($test2 =~ /$test1/) { print "YES!!! \n";}
else { print "NOOOO!!! \n"; }
这将打印NOOOO
my $test1 = 'mytest';
my $test2 = 'this is a mytest blah test';
if ($test2 =~ /$test1/) { print "YES!!! \n";}
else { print "NOOOO!!! \n"; }
这将打印YES!
我急需这个解决方案。
多谢
答
你真的需要的正则表达式?问题是,只是一个简单的字符串搜索...
if (index($test2, $test1) >= 0) { print "YES!!! \n";}
else { print "NOOOO!!! \n"; }
答
也许用 “\ Q” 试图逃跑的特殊字符
my $test1 = 'my?test';
my $test2 = 'this is a my?test blah test';
if ($test2 =~ /\Q$test1/) { print "YES!!! \n";}
else { print "NOOOO!!! \n"; }
输出中YES!!!
答
quotemeta可以处理特殊的正则表达式字符。
use warnings;
use strict;
my $test1 = quotemeta 'my?test';
my $test2 = 'this is a my?test blah test';
if ($test2 =~ /$test1/) { print "YES!!! \n";}
else { print "NOOOO!!! \n"; }
{
my $test1 = quotemeta 'mytest';
my $test2 = 'this is a mytest blah test';
if ($test2 =~ /$test1/) { print "YES!!! \n";}
else { print "NOOOO!!! \n"; }
}
打印:
YES!!! YES!!!
可能重复的[如何处理Perl正则表达式中的特殊字符?](http://stackoverflow.com/questions/576435/how-做-I-手柄特殊字符-IN-A-Perl的正则表达式) – daxim 2011-03-25 14:26:06