佚名通过本文主要向大家介绍了正则表达式匹配括号,正则匹配括号,正则表达式匹配大括号,正则表达式匹配小括号,正则表达式匹配中括号等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
问题:正则如何递归匹配大括号?
描述:
解决方案1:
描述:
我有一段字符串:
require './test.php';
function test() {
if (true) {
foreach ($arr as $v) {
// ...
}
}
}
echo 333;
test();
function test2() {
if (true) {
foreach ($arr as $v) {
// ...
}
} else {
// ...
}
}
即函数内有N多匹配的{}。
现在想正则匹配出以上字符串所有function,即函数{}包裹的字符串,如何操作?
麻烦PHP或Python示例,多谢。
解决方案1:
http://php.net/manual/en/book.tokenizer.php这组内置函数可以代替正则来解析php代码 会更快
解决方案2:我看题主的问题中虽然提到了递归,但其实只是说想要函数的大括号包裹的部分,好像并没有提到要把里面的if, foreach之类的语法也要分析出来,所以如果只是希望一个简单的实现的话,这样如何
<?php
$raw = <<<'EOT'
require './test.php';
function test() {
if (true) {
foreach ($arr as $v) {
// ...
}
}
}
echo 333;
test();
function test2() {
if (true) {
foreach ($arr as $v) {
// ...
}
} else {
// ...
}
}
EOT;
$matches = [];
preg_match_all('/function (\S+)\s?\{(.*?)\}/s', $raw, $matches);
print_r($matches);
运行结果
Array
(
[0] => Array
(
[0] => function test() {
if (true) {
foreach ($arr as $v) {
// ...
}
[1] => function test2() {
if (true) {
foreach ($arr as $v) {
// ...
}
)
[1] => Array
(
[0] => test()
[1] => test2()
)
[2] => Array
(
[0] =>
if (true) {
foreach ($arr as $v) {
// ...
[1] =>
if (true) {
foreach ($arr as $v) {
// ...
)
)
解决方案3:.net
中有平衡组可以实现任意层嵌套的匹配, php
和python
中的正则没有支持动态表达式语言,因此无法实现任意层嵌套的匹配