masato-san masato-san - 6 months ago 26
Javascript Question

How to capture multiple occurrence using capturing parenthesis

I'm trying to extract only the key string part "ProcessName" and "ProcessID" from the text.
text could have more key. (I'm just using the text with two keys for simplicity)
Is it possible to capture multiple occurrence of the group?

var text = "[ProcessName] - [ProcessID]";
var regex = new RegExp(/\[[(A-Za-z0-9)]+\]/g);
var result = regex.exec(text);

When I use exec, it gives me just one match and with the bracket so it has no use it seems.
enter image description here

Also tried match() but it contains square brackets. Tried many times but cannot seem to get it right.

var result = text.match(regex);

enter image description here


You mispositioned the round and square brackets, thus making a capture group part of the character class preventing the submatch to be created.

You need to swap the positions of the brackets:


See the regex demo and a JS demo below.

Pattern details:

  • \[ - a literal [
  • ([a-z0-9]+) - Group 1 capturing one or more alphanumerics
  • ] - a literal closing bracket (no need escaping it when it is outside a character class)
  • /gi - global and case insensitive matching modifiers ([a-z] will also match A-Z, processing each non-overlapping match)

var re = /\[([a-z0-9]+)]/gi; 
var str = '[ProcessName] - [ProcessID]';
var res = [];
while ((m = re.exec(str)) !== null) {

In the code, we need to use RegExp#exec rather than String#match because the latter, when used with a regex having a global modifier, will discard all submatches (captured parts) (see Description at MDN String#match page).