我需要用正则表达式找到一个正则表达式字符类(即方括号之间的所有内容)。所以我想出了以下正则表达式:
(?<!\\)\[(?:\^\])?(?:[^]\\]+|\\.)*\]
当我在 Notepad++ 中测试它时,该正则表达式工作得非常好——在搜索窗口 (Ctrl-F) 和 RegEx Helper 插件中——但是当我尝试在 PHP 代码中使用它时出现错误。
$string = '[^abcd\]efgh]';
$pattern = '/
(?<!\\) \[ # an opening square bracket not preceded by a backslash
(?:\^\])? # circumflex and closing bracket 0 or 1 times
(?:
[^]\\]+ # not a closing bracket, nor a backslash 1-n times
| # or
\\. # any escaped character (including an escaped closing bracket)
)* # 0-n times
\] # closing bracket
/x';
preg_match_all($pattern, $string, $matches);
print_r($matches);
输出:
警告:preg_match_all(): Compilation failed: missing terminating ] for character class at offset 33 in C:...\test.php on line 21
我哪里错了?