Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regex Global Match Groups

Update: This question is a near duplicate of this

I'm sure the answer to my question is out there, but I couldn't find the words to express it succinctly. I am trying to do the following with JavaScript regex:

var input = "'Warehouse','Local Release','Local Release DA'"; var regex = /'(.*?)'/g;  console.log(input.match(regex));  // Actual: // ["'Warehouse'", "'Local Release'", "'Local Release DA'"]  // What I'm looking for (without the '): // ["Warehouse", "Local Release", "Local Release DA"] 

Is there a clean way to do this with JavaScript regex? Obviously I could strip out the 's myself, but I'm looking for the correct way to caputre globally matched groupings with regex.

like image 355
Jondlm Avatar asked Nov 11 '13 18:11

Jondlm


People also ask

How do I match a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What is regex global match?

The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).

What is capturing group in regex Javascript?

A part of a pattern can be enclosed in parentheses (...) . This is called a “capturing group”. That has two effects: It allows to get a part of the match as a separate item in the result array.

What does .match do in Javascript?

The match() method returns an array with the matches. The match() method returns null if no match is found.


2 Answers

To do this with a regex, you will need to iterate over it with .exec() in order to get multiple matched groups. The g flag with match will only return multiple whole matches, not multiple sub-matches like you wanted. Here's a way to do it with .exec().

var input = "'Warehouse','Local Release','Local Release DA'"; var regex = /'(.*?)'/g;  var matches, output = []; while (matches = regex.exec(input)) {     output.push(matches[1]); } // result is in output here 

Working demo: http://jsfiddle.net/jfriend00/VSczR/


With certain assumptions about what's in the strings, you could also just use this:

var input = "'Warehouse','Local Release','Local Release DA'"; var output = input.replace(/^'|'$/, "").split("','"); 

Working demo: http://jsfiddle.net/jfriend00/MFNm3/


Note: With modern Javascript engines as of 2021, you can use str.matchAll(regex) and get all matches in one function call.

like image 94
jfriend00 Avatar answered Sep 22 '22 10:09

jfriend00


There is an ECMAScript proposal called String.prototype.matchAll() that would fulfill your needs.

like image 41
shaedrich Avatar answered Sep 20 '22 10:09

shaedrich