简体   繁体   English

javascript - 仅查找和替换匹配的右括号

[英]javascript - find and replace only matching closing bracket

I'm wondering if there's an elegant way to find and replace the matching brackets for code depending on what is adjacent to the opening bracket.我想知道是否有一种优雅的方法来查找和替换代码的匹配括号,具体取决于与左括号相邻的内容。 For example, I might want to convert:例如,我可能想转换:

// code for random_number() function
for(i in 1:5){
   print(i);
   mean(c(1,2,random_number()))
   sd(c(4,5,6))
}

into:进入:

// code for random_number() function
for(i in 1:5){
   print(i);
   mean([1,2,random_number()])
   sd([4,5,6])
}

because all I want to do is convert "c(1,2,3)" into "[1,2,3]" (and "c(4,5,6)" into "[4,5,6]").因为我想要做的就是将 "c(1,2,3)" 转换为 "[1,2,3]" (和 "c(4,5,6)" 转换为 "[4,5,6]" )。 I want to identify the closing bracket opposite "c(" in a script like this.我想在这样的脚本中识别与“c(”相对的右括号。

I don't want to change any of the other opening and closing brackets.我不想更改任何其他的开始和结束括号。 Is there an elegant way of doing this?有没有一种优雅的方式来做到这一点? The closest thing I found was Javascript replace opening and closing brackets , but it seemed more like a method to replace all brackets with the occasional exception, rather than specific brackets but ignoring most.我发现的最接近的东西是Javascript replace opening and closing brackets ,但它似乎更像是一种偶尔替换所有括号的方法,而不是特定的括号,但忽略了大多数。

My only thoughts are to count the opening and closing of brackets, but that seems quite ugly, to say the least.我唯一的想法是计算括号的开头和结尾,但至少可以这么说,这看起来很丑陋。 Is there a tidier way?有没有更整洁的方法?

You could use RegExp for that, something like: c\((([^)]*\([^)]*\))*[^)]*)\) Here is an example:您可以为此使用 RegExp,例如: c\((([^)]*\([^)]*\))*[^)]*)\)这是一个示例:

 const regExp = /c\((([^)]*\([^)]*\))*[^)]*)\)/g; const source = `// code for random_number() function for(i in 1:5){ print(i); mean(c(1,2,random_number())) sd(c(4,5,6)) }`; const result = source.replace(regExp, '[$1]') console.log(result);

This will probably fail with more complex source strings.这可能会因更复杂的源字符串而失败。

What it does, is to look for a c character followed by a ( character, then ignore all opening brackets that have a corresponding closing bracket and put all that along with any characters that are not a ) into a group and then look for a ) character.它的作用是查找c字符后跟一个(字符,然后忽略所有具有相应右括号的左括号,并将所有这些与任何不是 a 的字符一起放入一个组,然后查找) )特点。

Balancing parenthesis with regex is not a good idea, this works with only one level (fails when there are two opening parenthesis without a closing parenthesis between them).用正则表达式平衡括号不是一个好主意,这只适用于一个级别(当有两个左括号而它们之间没有右括号时会失败)。 A more reliable approach will be looping the string and keeping track of all the opening and closing brackets.更可靠的方法是循环字符串并跟踪所有开始和结束括号。

Beside all that, the regex doesn't distinguish between brackets that are part of code or those that are part of string literals.除此之外,正则表达式不区分作为代码一部分的括号或作为字符串文字一部分的括号。

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

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