Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Regex access multiple occurrences [duplicate]

Tags:

I have this text

txt = "Local residents o1__have called g__in o22__with reports..."; 

in which I need to get the list of numbers between each o and __

If I do

txt.match(/o([0-9]+)__/g); 

I will get

["o1__", "o22__"] 

But I'd like to have

["1", "22"] 

How can I do that ?

like image 680
Pierre de LESPINAY Avatar asked Sep 02 '11 07:09

Pierre de LESPINAY


2 Answers

See this question:

txt = "Local residents o1__have called g__in o22__with reports..."; var regex = /o([0-9]+)__/g var matches = []; var match = regex.exec(txt); while (match != null) {     matches.push(match[1]);     match = regex.exec(txt); } alert(matches); 
like image 58
Bobby Avatar answered Oct 07 '22 05:10

Bobby


You need to use .exec() on a regular expression object and call it repeatedly with the g flag to get successive matches like this:

var txt = "Local residents o1__have called g__in o22__with reports..."; var re = /o([0-9]+)__/g; var matches; while ((matches = re.exec(txt)) != null) {     alert(matches[1]); } 

The state from the previous match is stored in the regular expression object as the lastIndex and that's what the next match uses as a starting point.

You can see it work here: http://jsfiddle.net/jfriend00/UtF6J/

Using the regexp this way is described here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec.

like image 23
jfriend00 Avatar answered Oct 07 '22 05:10

jfriend00