views:

43

answers:

3
text = 'ticket number #1234 and #8976 ';
r = /#(\d+)/g;

var match = r.exec(text);

log(match); // ["#1234", "1234"]

In the above case I would like to capture both 1234 and 8976. How do I do that. Also the sentence can have any number of '#' followed by integers. So the solution should not hard not be hard coded assuming that there will be at max two occurrences.

Update: Just curious . Checkout the following two cases.

var match = r.exec(text); // ["#1234", "1234"]

var match = text.match(r);  //["#1234", "#8976"]

Why in the second case I am getting # even though I am not capturing it. Looks like string.match does not obey capturing rules.

+1  A: 

Use String.prototype.match instead of RegExp.prototype.exec:

var match = text.match(r);

That will give you all matches at once (requires g flag) instead of one match at a time.

Gumbo
+1  A: 

exec it multiple times to get the rest.

while((match = r.exec(text)))
  log(match);
KennyTM
Better compare to `null`: `while ((match = r.exec(text)) !== null)`
Gumbo
A: 

Here's another way

var text = 'ticket number #1234 and #8976 ';
var r = /#(\d+)/g;

var matches = [];
text.replace( r, function( all, first ) {
    matches.push( first )
});

log(matches);

//  ["1234", "8976"]
meouw