I have the following string:
[group][100][250][3][person]
and I need to increment the number 3
. I tried the regex /\\[\\d+\\]/
which matches all 3, but I couldn't get anywhere from here.
You could do it by matching all 3 of your numeric values and just increment the third:
var regex = /\\[(\\d+)\\]\\[(\\d+)\\]\\[(\\d+)\\]/g var input = "[group][100][250][3][person]"; var result = input.replace(regex, function(match,p1,p2,p3){ return "[" + p1 + "][" + p2 + "][" + (parseInt(p3,10) + 1) + "]" }) console.log(result);
You can use .replace
with a callback function:
var s = "[group][100][250][3][person]"; var repl = s.replace(/((?:\\[\\d+\\]){2}\\[)(\\d+)\\]/, function($0, $1, $2) { return $1 + (parseInt($2)+1) + ']'; } ); console.log(repl); //=> "[group][100][250][4][person]"
To capture "your" string, try the below regex:
(?:\[\d+\]){2}\[(\d+)\]
How it works:
(?:...){2}
- a non-capturing group, occuring 2 times. \\[\\d+\\]
- containing [
, a sequence of digits and ]
. [
, a capturing group - sequence of digits and ]
. The text you want to capture is in the first capturing proup.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.