我想捕捉匹配的花括号。
例如:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="prf">
<label id='lblreason'></label>
<input type='text' id='reason' />
<label id='lbldate'></label>
<input type='date' id='date' placeholder='mm/dd/yyyy'>
</div>
<select id="status">
<option>Outstanding</option>
<option disabled=''>Served</option>
<option>Cancelled</option>
<option>Hold</option>
</select>
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"
则忽略它。但我不知道如何创建一个正则表达式来单独匹配花括号。
答案 0 :(得分:2)
要匹配成对的大括号,您需要使用recursive subpattern。
示例:强>
$regex = <<<'REGEX'
/
\\added\[.*?\] # Initial \added[author]
( # Group to be recursed on.
{ # Opening brace.
( # Group for use in replacement.
((?>[^{}]+)|(?1))* # Any number of substrings which can be either:
# - a sequence of non-braces, or
# - a recursive match on the first capturing group.
)
} # Closing brace.
)
/xs
REGEX;
$strings = [
'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 {}'
];
foreach ($strings as $string) {
echo preg_replace($regex, '$2', $string), "\n";
}
<强>输出:强>
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 {}
答案 1 :(得分:2)
在这里,应该工作
/\\added\[.*\]\{(.*(?:.*\{.*\}.*)*)\}/gU
<强>解释强>
/\\added\
是Latex标签,
\[.*\]
是Latex标签的选项,
\{
开括号,
(.*(?:.*\{.*\}.*)*)
是捕获的文本,我们在此处也阻止了目标代码中的递归{...}
或多个{...}
,
\}
关闭括号。
<强>策略强>
我不认为对括号是一种递归形式
{ { {...} } }
c b a a b c
我们有a
,b
和c
,
但我认为他们是这样的!
{ { {...} } }
a b c a b c
请参阅:DEMO
我的演示中的最后两个示例也证明它可以正常工作。
重要:修饰符U
假设在这里用于非贪婪量词的目的,否则我的正则表达式将无法正常工作。
答案 2 :(得分:1)
使用以下正则表达式:
\\\\added\\[[^\\]]\*][^\\{]\*{((?:(?:[^\\{\\}]\*\\{[^\\}\\{]\*\\})\*||[^\\}]\*)\*)}
答案 3 :(得分:0)