gpt4 book ai didi

php - 正则表达式:捕获成对的花括号

转载 作者:可可西里 更新时间:2023-10-31 22:53:09 24 4
gpt4 key购买 nike

我想捕获匹配的大括号。

例如:

Some example text with \added[author]{text with curly braces{some text}..}

Some example text with \added[author]{text without curly braces}

Some example text with \added[author]{text with {}and {} and {}curly braces{some text}..}

Some example text with \added[author]{text with {}and {} and {}curly braces{some text}..} and extented text with curly braces {}

预期输出:

Some example text with text with curly braces{some text}..

Some example text with text without curly braces

Some example text with text with {}and {} and {}curly braces{some text}..

Some example text with text with {}and {} and {}curly braces{some text}.. and extented text with curly braces {}

即我想捕获 \added[]{ 之间的文本和 } (它的相对闭合花括号)。我的正则表达式的问题是,我不知道如何在相关的花括号之间进行捕获。

我试过了,

       "/\\\\added\\[.*?\\]{(.[^{]*?)}/s"

我知道它会忽略 if {出现在文中。但我不知道如何创建一个正则表达式来单独匹配花括号。

最佳答案

在这里,应该工作

/\\added\[.*\]\{(.*(?:.*\{.*\}.*)*)\}/gU

解释

/\\added\是一个Latex标签,

\[.*\]是Latex标签的一个选项,

\{ 左括号,

(.*(?:.*\{.*\}.*)*) 是捕获的文本,我们在这里也防止递归 {...} 或目标标签内的多个 {...}

\} 右括号。​​

策略

我不认为括号对是递归形式

{ { {...} } }
c b a a b c

我们有对 abc

但我认为他们是这样的!

{ { {...} } }   
a b c a b c

参见:DEMO

我的demo中的最后两个例子也证明了它可以正常工作。

重要修饰符 U 应该在这里用于非贪婪量词,否则我的正则表达式将无法正常工作。

关于php - 正则表达式:捕获成对的花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32329190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com