Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 与方括号中最后一个数字匹配的JS正则表达式_Javascript_Jquery_Regex_String_Regex Lookarounds - Fatal编程技术网

Javascript 与方括号中最后一个数字匹配的JS正则表达式

Javascript 与方括号中最后一个数字匹配的JS正则表达式,javascript,jquery,regex,string,regex-lookarounds,Javascript,Jquery,Regex,String,Regex Lookarounds,在表单中,我有一个动态表,可以在其中添加或删除每个单元格中带有字段的行。每次我添加/删除一行时,它都会更新每个的名称 名称如下:sheet[折扣][0][base] 我只想更改这个字符串的[0](不是完全匹配,而是方括号中的数字) 我找到了正确的正则表达式: var name = $(input).attr('name'); var str = name.replace(/\[\d+\]/, '[' + index + ']'); 但我也有更复杂的输入名称,比如:sheet[cci][0][t

在表单中,我有一个动态表,可以在其中添加或删除每个单元格中带有字段的行。每次我添加/删除一行时,它都会更新每个
名称

名称如下:
sheet[折扣][0][base]

我只想更改这个字符串的
[0]
(不是完全匹配,而是方括号中的数字)

我找到了正确的正则表达式:

var name = $(input).attr('name');
var str = name.replace(/\[\d+\]/, '[' + index + ']');
但我也有更复杂的输入名称,比如:
sheet[cci][0][terms][0][commit]

我只想更改方括号中数字的最后一次出现:

// replace this
sheet[cci][0][terms][0][commit]

// by this
sheet[cci][0][terms][1][commit]

字符串结尾之前的
[\d+]
的负前瞻:

const index=7;
`表[cci][0][条款][1][commit]
表[cci][0][条款][2][commit]
表[cci][0][terms][3][commit]`.split('\n').forEach((str)=>{
console.log(
str.replace(/\[\d+\](?!.\[\d+\])/,“['+索引+”])
)

});使用贪心点消费(并匹配)直到最后一个
[0]

var name='sheet[cci][0][terms][0][commit];
var指数=3;
var str=name.replace(/(.*)\[\d+\]/,“$1['+index+']);

console.log(str)
使用
name.replace(/(.*)\[\d+\]/,“$1['+index+'])
您的上一句话使您的问题变得模棱两可:更改
[0]
(不需要
\d
)的最后一次出现或更改
\[\d\]
?更改方括号中最后出现的数字。@Felurian如果使用我的代码,它会起作用。您未能在替换中添加
$1
。@WiktorStribiżew是的,很抱歉,我在写评论后看到了我的错误。谢谢,它可以工作。最后一个
(.*)
$2
是多余的。看。谢谢,它是有效的,它的答案与@WiktorStribiżew;-)相同是的,方括号里只有数字,其他都是字母。