Reputation: 307
I'm not able to get an array from the result of a regex match:
var txt = '[Eig2]=>100 [Eig1]=="test"';
var reg = '(\\[)((?:[a-z][a-z]+))(\\d+)(\\])';
var m = txt.match(new RegExp(reg, ["i"]));
if (m != null) {
for (var i = 0; i < m.length; i++) {
console.log(m[i]);
}
} else {
console.log("null");
}
What it returns:
[Eig2]
[
Eig
2
]
What I want:
[Eig2]
[Eig1]
May I have to do it without "new RegExp", but with "/([)((?:[a-z][a-z]+))(\d+)(])/g" it does not work...
Some ideas?
Regards
Upvotes: 1
Views: 186
Reputation: 173562
First, I would simplify the expression:
var re = /\[([a-z]{2,}\d+)\]/ig;
I've added the /i
for case insensitive matching and /g
modifier to match multiple occurrences. Then you call it like this:
> txt.match(re);
["[Eig2]", "[Eig1]"]
To extract the first memory capture:
var captures = [];
txt.replace(re, function($0, $1) {
captures.push($1);
});
Granted, .replace()
is being abused here
Then, evaluate captures:
> captures
["Eigh2", "Eigh1"]
Update
A somewhat friendlier way to build the array of memory captures:
var captures = [], match;
while ((match = re.exec(txt)) !== null) {
captures.push(match[1]);
});
Upvotes: 2
Reputation: 266
You should modify
var m = txt.match(new RegExp(reg, ["i"]));
to
var m = txt.match(new RegExp(reg, ["ig"]));
Add the g
flag to your regular expression, which means you want to match all patterns in the string, instead of the first one and its subpatterns.
Upvotes: 2