简体   繁体   English

无法使用RegEx将索引值放在方括号内

[英]Can't put index value inside brackets using RegEx

There are two strings. 有两个字符串。 I'm trying to put index value inside empty brackets: 我试图将索引值放在空括号内:

var capacity = 'room[price_group_ids][][capacity]';
var group = 'room[price_group_ids][][group][%s][]';

For example, If an index is 1, they should be: 例如,如果索引为1,则它们应为:

var capacity = 'room[price_group_ids][1][capacity]';
var group = 'room[price_group_ids][1][group][%s][]';

And if the index is 2, they should look like as the following: 如果索引为2,则它们应如下所示:

var capacity = 'room[price_group_ids][2][capacity]';
var group = 'room[price_group_ids][2][group][%s][]';

What I've tried and it gives unexpected result: 我尝试过的结果给了意外的结果:

var index = 2;

var capacity = 'room[price_group_ids][][capacity]'.replace(/\[(.+?)\]/g, "[" + index +"]"); // Should become room[price_group_ids][2][capacity]
var group = 'room[price_group_ids][][group][%s][]'.replace(/\[(.+?)\]/g, "[" + index +"]"); // Should become room[price_group_ids][2][group][%s][]

I'm not good at RegEx and looking for an advice on how to resolve that 我不擅长RegEx,并寻求有关如何解决该问题的建议

A simple replace should work here. 一个简单的replace应该在这里工作。

This will only replace the first occurrence of [] , so you don't have to worry about others. 这只会替换[]的第一次出现,因此您不必担心其他人。 g flag is used to replace globally ie all the occurrences of the specified value g标志用于全局替换,即所有出现的指定值

capacity.replace('[]', `[${index}]`);

 var index = 2; var capacity = 'room[price_group_ids][][capacity]'; var group = 'room[price_group_ids][][group][%s][]'; capacity = capacity.replace('[]', `[${index}]`); group = group.replace('[]', `[${index}]`); console.log(capacity) console.log(group) 

Since you want to match first occurrence of [] so don't use g flag. 由于您想匹配[]首次出现,因此请勿使用g标志。 Also no need to match anything else (.+?) , just /\\[\\]/ is enough. 也不需要匹配其他任何内容(.+?) ,只需/\\[\\]/就足够了。

Another way is to simply replace string [] with [1] 另一种方法是将字符串[]替换为[1]

 let index = 2 console.log('room[price_group_ids][][capacity]'.replace(/\\[\\]/, `[${index}]`)); console.log('room[price_group_ids][][group][%s][]'.replace(/\\[\\]/, `[${index}]`)); 

The reg exp /\\[(.+?)\\]/g matches 1-or-more of anything between [] brackets. reg exp /\\[(.+?)\\]/g匹配[]括号之间的1个或多个/\\[(.+?)\\]/g You want to detect [ and ] right next to each other; 您想彼此相邻检测[] simply: 只是:

/\[\]/

Also, you want to ditch the g at the end, unless you want the replacement to occur for all occurrences of [] -- the g means global . 另外,除非要对所有出现的[] 进行替换,否则您要在结尾处放弃g - g表示global

But there are non-regex approaches, too, as shown in the other answers. 但是,也有非正则表达式方法,如其他答案所示。

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

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