[英]regex for group of square brackets and comma javascript
I'm trying to construct a regular expression which I can use to replace all instances of "],[" with just "," in a string.我正在尝试构建一个正则表达式,我可以用它来替换字符串中的所有“],[”实例,只用“,”。
I'm stuck on this.我坚持这一点。
I've been through a number of different combinations - currently trying:我经历了许多不同的组合 - 目前正在尝试:
str.replace(/(\[,\])/, ',');
But it's not picking it up and I can't see what's wrong with it - anything obvious I'm doing wrong here?但它没有捡起它,我看不出它有什么问题 - 有什么明显的我做错了吗?
Thanks谢谢
You are using the brackets in wrong order and you need to match multiple occurrences with the g
flag.您以错误的顺序使用括号,并且需要将多次出现与g
标志匹配。
So you may use所以你可以使用
text = text.replace(/],\[/g, ',')
Or, if you want to use a capturing group,或者,如果您想使用捕获组,
text = text.replace(/](,)\[/g, '$1')
See regex demo #1 and regex demo #2 .请参阅正则表达式演示 #1和正则表达式演示 #2 。
NOTE : If there may be any amount of whitespace between the brackets, use \s*
to match it, eg text = text.replace(/]\s*,\s*\[/g, ',')
.注意:如果括号之间可能有任何数量的空格,请使用\s*
来匹配它,例如text = text.replace(/]\s*,\s*\[/g, ',')
。
JS demo: JS 演示:
var text = "text],[text2],[text3"; console.log(text.replace(/],\[/g, ',')); console.log(text.replace(/](,)\[/g, '$1'));
Your square brackets are positioned wrongly, and you don't need the normal brackets.您的方括号位置错误,您不需要普通括号。
Let's go in steps:让我们按步骤 go:
],[
so you need to use the following:您想替换],[
的所有实例,因此您需要使用以下内容:/],[/g
The g
in the regexp is ensures that all instances are replaced.正则表达式中的g
确保所有实例都被替换。
[
and ]
are special characters, so you use \
to stop regexp from parsing them: [
和]
是特殊字符,因此您使用\
来阻止正则表达式解析它们:/\],\[/g
Final Result:最后结果:
let str = '[myString],[AnotherString]'; str = str.replace(/\],\[/g, ","); console.log(str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.