How to Write Regex to match third array element

Viewed 58

I need help to write a regex that helps me to match the third array key.

For example Array name : soundConfig[0][songs][1][html] regex to match first key element [0] => /\[(\d+)\]/

I want to match the third array element [1]

Thanks in advance,

2 Answers

Using match() with the pattern \[.*?\] we can try:

var input = "soundConfig[0][songs][1][html]";
var parts = input.match(/\[.*?\]/g);
console.log(parts[2]);

If instead your goal is to replace the third array index with something else, then use string split followed by a join:

var input = "soundConfig[0][songs][1][html]";
var parts = input.split(/(?=\[)/);
var output = parts.slice(0, 3).join("") + "[NEW]" + parts.slice(4, 5).join("");
console.log(output);

If you want to replace the third value, you could also use a capture group and use a negated character class to match from [ till ]

In the replacement use group 1 $1 followed by the replacement.

^(\w+(?:\[[^\][]*]){2}\[)[^\][]*(?=])

The pattern matches:

  • ^ Start of string
  • ( Capture group 1 (Referred to by $1 in the replacement code)
    • \w+ Match 1+ word chars
    • (?:\[[^\][]*]){2} Repeat 2 times matching [...]
    • \[ Match the opening [ for the third part
  • ) Close group 1
  • [^\][]* Match till the closing ] (which is the part you want to replace)
  • (?=]) Positive lookahead, assert the closing ] for the third part at the right

Regex demo

const regex = /^(\w+(?:\[[^\][]*]){2}\[)[^\][]*(?=])/;
const str = `soundConfig[0][songs][1][html]`;
console.log(str.replace(regex, `$1REPLACEMENT`));

Or if the first and the third part have to be a digit and according to the comment you want to increment the value, you can use 2 capture groups.

^(\w+\[\d+]\[\w+]\[)(\d+)(?=])

Regex demo

const regex = /^^(\w+\[\d+]\[\w+]\[)(\d+)(?=])/;
const str = `soundConfig[0][songs][1][html]`;
console.log(str.replace(regex, (_, g1, g2) => `${g1}${++g2}`));

Related