使用正则表达式查找正则表达式字符类


Find a regex character class with a regex

我需要找到一个带有正则表达式的正则表达式字符类(即方括号之间的所有内容)。因此,我提出了以下正则表达式:

(?<!'')'[(?:'^'])?(?:[^]'']+|''.)*']

当我在Notepad++中测试regex时,无论是在搜索窗口(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():编译失败:缺少终止]用于偏移33英寸处的字符类C: 。。。''第21行上的test.php

我哪里错了?

文字反斜杠需要在PHP正则表达式中用四个反斜杠表示。因此,尝试

$pattern = '/(?<!'''')'[(?:'^'])?(?:[^]'''']+|''''.)*']/'