需要有关正则表达式的帮助。
字符串: (可以包含更多级别的“测试”)
[test]
[inner]
[test]
[inner]*anything*
[/inner]
[/test]
[/inner]
[/test]
[test]
[inner]*anything*
[/inner]
[/test]
应匹配:
1
[test]
[inner]
[test]
[inner]*anything*
[/inner]
[/test]
[/inner]
[/test]
2
[test]
[inner]*anything*
[/inner]
[/test]
问题:
如何在PHP中编写与想要的结果匹配的正则表达式?
这是我的例子: https://regex101.com/r/tA2wN8/2
答案 0 :(得分:1)
您需要使用递归模式:
~\[test](?:[^[]+|\[(?!/?test])|(?R))*+\[/test]~
细节:
~ # pattern delimiter
\[test]
(?: # non-capturing group (possible content between test tags)
[^[]+ # all that is not a [
|
\[(?!/?test]) # a [ not part of a test tag (opening or closing)
|
(?R) # repeat the whole pattern (recursion)
)*+ # repeat the group zero or more times (possessive quantifier)
\[/test]
~
注意这种方式只能用PHP或Perl,Javascript没有办法没有递归功能。