clarkk
clarkk

Reputation: 1

How to match multiple sequences

How is it possible to match more than one string with regular expressions?

Here I want to match both name and txt, but only name is matched?

var reg = new RegExp('%([a-z]+)%', "g");
reg.exec('%name% some text %txt%');

Upvotes: 0

Views: 70

Answers (3)

user1726343
user1726343

Reputation:

Use match instead:

'%name% %txt%'.match(reg); //["%name%", "%txt%"]

exec only retrieves the first match (albeit with capturing groups).

If the capturing groups are important to you, you can use a loop:

var matches = [];
var str = '%name% some text %txt%';
var reg = new RegExp('%([a-z]+)%', "g");
while (match = reg.exec(str)){
    matches.push(match);
}

If you only want to keep the captured groups, use this instead:

matches.push(match[1]);

Upvotes: 3

Bruno
Bruno

Reputation: 5822

The g flag does work but needs to be executed on the same string multiple times

var reg = new RegExp('%([a-z]+)%', "g");
var str = '%name% some text %txt%';
var result;

while( result = reg.exec( str ) ) { // returns array of current match
    console.log( result[1] ); // index 0 is matched expression. Thereafter matched groups.
}​

The above outputs name & txt to the console.

Example here

Upvotes: 1

Jon
Jon

Reputation: 437664

You need to use String.match instead of exec:

'%name% some text %txt%'.match(reg);

Upvotes: 3

Related Questions