使用RegExp匹配括号,然后递增它 [英] Use RegExp to match a parenthetical number then increment it
问题描述
我一直试图找到一种方法来匹配字符串末尾括号内的Javascript字符串中的数字,然后递增它。
I've been trying to find a way to match a number in a Javascript string that is surrounded by parenthesis at the end of the string, then increment it.
说我有一个字符串:
var name = "Item Name (4)";
我需要一个RegExp来匹配(4)部分,然后我需要增加4然后把它放回字符串。
I need a RegExp to match the (4) part, and then I need to increment the 4 then put it back into the string.
这是我到目前为止的正则表达式:
This is the regex I have so far:
\b([0-9]+)$\b
这个正则表达式不起作用。此外,我不知道如何提取检索到的整数并将其放回字符串中的相同位置。
This regex does not work. Furthermore, I do not know how to extract the integer retrieved and put it back in the same location in the string.
谢谢。
推荐答案
replace方法可以将函数作为其第二个参数。它获取匹配(包括子匹配)并返回替换字符串。其他人已经提到括号需要转义。
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) + ")";
});
这篇关于使用RegExp匹配括号,然后递增它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!