我以爲php的perl兼容正則表達式(preg庫)支持大括號作爲分隔符。這應該是罰款:Php正則表達式與安全分隔符
{ello {world}i // should match on Hello {World
大括號的主要觀點是,只需要最左和右的,因此不需要轉義內的。據我所知,PHP需要轉義
{ello \{world}i // this actually matches on Hello {World
這是預期的行爲或PHP preg實施中的錯誤?
我以爲php的perl兼容正則表達式(preg庫)支持大括號作爲分隔符。這應該是罰款:Php正則表達式與安全分隔符
{ello {world}i // should match on Hello {World
大括號的主要觀點是,只需要最左和右的,因此不需要轉義內的。據我所知,PHP需要轉義
{ello \{world}i // this actually matches on Hello {World
這是預期的行爲或PHP preg實施中的錯誤?
當您在Perl中使用四個配對的ASCII括號類型中的任意一個模式分隔符時,只需在模式中轉義未配對括號。這實際上是使用括號的全部目的。
Non-bracketing delimiters use the same character fore and aft,
but the four sorts of brackets (round, angle, square, curly)
will all nest, which means that
q{foo{bar}baz}
is the same as
'foo{bar}baz'
Note, however, that this does not always work for quoting Perl code:
$s = q{ if($a eq "}") ... }; # WRONG
這就是爲什麼你經常看到有人在Perl代碼中使用m{…}
或qr{…}
,尤其是對於使用多模式:這是在perlop中手冊頁「報價和報價般的運營商」,其內容部分下記錄與/x
ᴀᴋᴀ(?x)
。例如:
return qr{
(?= # pure lookahead for conjunctive matching
\A # always from start
. *? # going only as far as we need to to find the pattern
(?:
${case_flag}
${left_boundary}
${positive_pattern}
${right_boundary}
)
)
}sxm;
請注意,這些嵌套大括號是沒有問題的。
據我所知,期望的行爲,否則編譯器將如何允許組限制器?例如
[a-z]{1,5}
我發現,沒有逃脫在這種情況下需要:
'ello {world'i
(ello {world)i
所以我的理論是,這個問題是與「{」只有分隔符。此外,下面的兩個產生相同的誤差:
{ello {world}i
(ello (world)i
使用開始/結束括號作爲分隔符可能需要逃脫在表達式給定的大括號。
從http://lv.php.net/manual/en/regexp.reference.delimiters.php:
If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.
所以這是預期的行爲,不是一個錯誤。
from http://perldoc.perl.org/perlre.html - 「如果在任何其他上下文中出現花括號,則將其視爲常規字符。」 – binaryLV 2011-02-08 08:29:23