如何通过正则表达式增加匹配的数字? [英] How can I increment a number matched via regex?

查看:117
本文介绍了如何通过正则表达式增加匹配的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在其中一个网络应用中添加了一个新字段,供访问者添加产品。推送添加产品克隆其中一个现有输入,并将其设置为空白值。

I am adding a new field in one of my web apps, for visitors to add a product. Pushing "add a product" clones one of the existing inputs, and I set it to a blank value.

我需要更新名称。名称采用以下格式:

I need to update the name however. The name is in this format:

<input type="text" name="product[0][0][3][title]" value="my product" id="input-AbGHtQS3" maxlength="150" />

我需要增加最后一个数字索引,即本例中的3。

I need to increment the last numerical index, that is the 3 in this example.

我写了一个正则表达式来匹配相应的字符,但是如何递增最后一个数字呢?

I wrote a regex to match the appropriate character, but how can I increment that last number?

这是我的正则表达式:

Here is my regex:

/^product\[\d+\]\[\d+\]\[(\d+)\]\[.+\]/

我怎么能增加最后一个号码?

How could I increment that last number?

推荐答案

来自:使用RegExp匹配括号,然后将其递增

替换方法可以将函数作为其第二个参数。它获取匹配(包括子匹配)并返回替换字符串。其他人已经提到括号需要转义。

The replace method can take a function as its second argument. It gets the match (including submatches) and returns the replacement string. Others have already mentioned that the parentheses need to be escaped.

"Item Name (4)".replace(/\((\d+)\)/, function(fullMatch, n) {
    return "(" + (Number(n) + 1) + ")";
});

所以,

*编辑:

这应该有用

"product[0][0][3][title]".replace(/(^product\[\d+\]\[\d+\]\[)(\d+)(\]\[.+\])/, function(fullMatch, n, a, o) {
    return n + (Number(a) + 1) + o;
});

这篇关于如何通过正则表达式增加匹配的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆