【问题标题】:How to match paired closing bracket with regex如何将配对的右括号与正则表达式匹配
【发布时间】:2016-04-01 13:14:38
【问题描述】:

我当前的正则表达式匹配一个函数名和传递给函数see here的变量名

正则表达式 - (file_exists|is_file)\(([^)]+)
字符串 if (is_file($file)){
匹配项 is_file$file

我还希望正则表达式使用字符串而不仅仅是变量名,这包括带有多个左括号和右括号的字符串。

这是一个极端的例子。

正则表达式 - (file_exists|is_file)\(????????)
字符串 if (is_file(str_replace(array('olddir'), array('newdir'), strtolower($file))){
匹配项 is_filestr_replace(array('olddir'), array('newdir'), strtolower($file)

有没有办法匹配下一个右括号,除非已经打开?

我想让它在regex101 工作

【问题讨论】:

  • 那么,您需要 PHP 的正则表达式吗?注意if (is_file(str_replace(array(), array(), strtolower($file))){里面没有str_replace(array('olddir'), array('newdir'), strtolower($file)
  • @WiktorStribiżew 谢谢,这是最后一分钟的编辑。我正在使用 vqmod 来查找和替换 php 文件。
  • 那么正则表达式的风格是什么?
  • @WiktorStribiżew 可以很好地工作。感谢您。请留下答案,以便我接受。

标签: php regex vqmod


【解决方案1】:

您可以在 PHP 中将正则表达式与子例程调用一起使用:

'~(file_exists|is_file)(\(((?>[^()]++|(?2))*)\))~'

regex demo

模式匹配:

  • (file_exists|is_file) - 两种选择之一
  • (\(((?>[^()]++|(?2))*)\)) - 第 1 组匹配成对的嵌套 (...) 子字符串,((?>[^()]++|(?2))*) 是第 3 组,捕获外部配对 (...) 内的内容。

因此,结果是:

  • 第 1 组:is_file
  • 第 2 组:(str_replace(array(), array(), strtolower($file)))
  • 第 3 组:str_replace(array(), array(), strtolower($file))

使用第 1 组和第 3 组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多