2011-02-28 169 views
0

簡單的問題(我希望)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!

我急需這個解決方案。

多謝

+0

可能重複的[如何處理Perl正則表達式中的特殊字符?](http://stackoverflow.com/questions/576435/how-做-I-手柄特殊字符-IN-A-Perl的正則表達式) – daxim 2011-03-25 14:26:06

回答

7

真的需要的正則表達式?問題是,只是一個簡單的字符串搜索...

if (index($test2, $test1) >= 0) { print "YES!!! \n";} 
else {  print "NOOOO!!! \n"; } 
4

也許用 「\ 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!!!

3

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!!!

1

你有沒有在CPAN尋找現有的模塊,可以幫助你嗎?從PerlMonks,我發現引用Apache :: ParseLog和Apache :: LogRegEx