簡體   English   中英

Perl正則表達式-動態正則表達式中的特殊字符

[英]Perl Regular Expression - Special Characters in Dynamic Regex

簡單的問題(我希望)

我有一個包含符號的動態字符串:?,/等,基本上是我的Apache錯誤文件中日志行中的URL字符串

我正在解析日志文件,我想查看該行中是否存在某個URL實例:

要搜索的網址行:“ http://www.foo.com?blah”

問號讓我失望,就像正則表達式中的任何特殊字符一樣。 我正在嘗試以下方法:

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";  }

這打印是!!!

我需要快速解決方案。

謝謝一大堆

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

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

您是否在CPAN中尋找可以幫助您的現有模塊? PerlMonks中 ,我找到了對Apache :: ParseLog和Apache :: LogRegEx的引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM