Reputation: 3829
I have this string
(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)
Using JavaScript, what is the fastest way to parse this into
[b, 10, c, x, y]
Upvotes: 3
Views: 124
Reputation: 387567
var str = '(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>) ';
var arr = str.match(/<<(.*?)>>/g);
// arr will be ['<<b>>', '<<10>>', '<<c>>', '<<x>>', '<<y>>']
arr = arr.map(function (x) { return x.substring(2, x.length - 2); });
// arr will be ['b', '10', 'c', 'x', 'y']
Or you can also use exec
to get the capture groups directly:
var regex = /<<(.*?)>>/g;
var match;
while ((match = regex.exec(str))) {
console.log(match[1]);
}
This regular expression has the benefit that you can use anything in the string, including other alphanumerical characters, without having them matched automatically. Only those tokens in << >>
are matched.
Upvotes: 3
Reputation: 253308
I'd suggest:
"(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)".match(/[a-z0-9]+/g);
// ["b", "10", "c", "x", "y"]
References:
Upvotes: 5
Reputation: 74096
Try this:
'(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)'.match(/[^(<+>)*-]+/g)
Upvotes: 5