如何将成对的右括号与正则表达式匹配
How to match paired closing bracket with regex
我当前的正则表达式匹配一个函数名和传递给该函数的变量名 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_file
和str_replace(array('olddir'), array('newdir'), strtolower($file)
有没有办法匹配下一个右括号,除非已经打开了?
我想让它在 regex101
工作
您可以在 PHP:
中使用带有子例程调用的正则表达式
'~(file_exists|is_file)(\(((?>[^()]++|(?2))*)\))~'
模式匹配:
(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 组。
我当前的正则表达式匹配一个函数名和传递给该函数的变量名 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_file
和str_replace(array('olddir'), array('newdir'), strtolower($file)
有没有办法匹配下一个右括号,除非已经打开了?
我想让它在 regex101
工作您可以在 PHP:
中使用带有子例程调用的正则表达式'~(file_exists|is_file)(\(((?>[^()]++|(?2))*)\))~'
模式匹配:
(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 组。