Question

If I have a multiple match regex like:

var matches = string.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i);

and if my string that I am testing is like this:

var string = "match1 match3";

is there a way to output this array values:

matches[1] = "match1";
matches[2] = "";
matches[3] = "match3";

Notice: what I would like is for the regex to match the entire thing but "place-hold" in the array the matches it does not find.

Hope this makes sense. Thanks for the help!

Was it helpful?

Solution

There already is a "placeholder". Unmatched groups pop an array index matching the group number with an undefined value. e.g.

var someString = "match2";
var matches = someString.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i);

matches now has

["match2", undefined, "match2", undefined]

Element 0 is the complete regex match and elements 1-3 are the individual groups

So you can do for example...

// check if group1
if (typeof matches[1] != 'undefined')

OTHER TIPS

When you want to compare the string to the regexes, just do an Array join.Something like,

matches[1] = "match1"; 
matches[2] = "";
matches[3] = "match3";
var mystring = mathches.join("");

The joining character could be anything. You could also do,

var mystring = mathches.join(" ");

EDIT: Not sure from the problem description, but i think you want the regex to output an array.Something like

 text = "First line\nSecond line";
 var regex = /(\S+) line\n?/y;

would give,

var match = regex.exec(text);
print(match[1]);  // prints "First"
print(regex.lastIndex); // prints 11

More about it here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top