简体   繁体   English

正则表达式仅替换嵌套括号的外括号

[英]regex replace only outer brackets of nested parenthesis

Looking to preserve inner nested brackets when replacing brackets.更换括号时希望保留内部嵌套括号。 If possible to make many nested layers work that would be great, if not just nested once is fine.如果可能使许多嵌套层工作会很棒,如果不只是嵌套一次就可以了。

(if money>5 and (times + total_cash >266))[something]
(if times + total_cash >266)[something]

{if money>5 and (times + total_cash >266)}[something]
{if times + total_cash >266}[something]

A naive attempt doesn't seem to work that well:天真的尝试似乎效果不佳:

str.replace(/\(if(.*?)\)]/gi, '{if $1}')

for zero level of nesting:对于零级嵌套:

str.replace(/\(if\s*([^()]*)\)/gi, '{if $1}')

for one level (or less):一级(或更少):

str.replace(/\(if\s*([^()]*(?:\([^()]*\)[^()]*)*)\)/gi, '{if $1}')

for two levels (or less):两个级别(或更少):

str.replace(/\(if\s*([^()]*(?:\([^()]*(?:\([^()]*\)[^()]*)*\)[^()]*)*)\)/gi, '{if $1}')

etc. This method becomes quickly limited.等等。这种方法很快就会受到限制。

Javascript regexes don't have features like recursive patterns (perl, pcre), or a counter system like in .net languages. Javascript 正则表达式不具有递归模式(perl、pcre)或 .net 语言中的计数器系统等功能。 That's why, the best option is to build a state machine to count the number of opening and closing parenthesis (note that you can use a regex to split your string to interesting parts to do it, for example: str.split(/(\bif\b|[()])/i) ).这就是为什么,最好的选择是构建一个 state 机器来计算左括号和右括号的数量(请注意,您可以使用正则表达式将字符串拆分为有趣的部分来执行此操作,例如: str.split(/(\bif\b|[()])/i) )。


Note that [^()]*(?:\([^()]*\)[^()]*)* is an optimized way to write: (?:[^()]|\([^()]*\))* (that is shorter but inefficient).请注意, [^()]*(?:\([^()]*\)[^()]*)*是一种优化的编写方式: (?:[^()]|\([^()]*\))* (更短但效率低)。 This subpattern is unrolled .此子模式已展开

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM