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]
I'd suggest:
"(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)".match(/[a-z0-9]+/g);
// ["b", "10", "c", "x", "y"]
References:
尝试这个:
'(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)'.match(/[^(<+>)*-]+/g)
use regex
var pattern=/[a-zA-Z0-9]+/g
your_string.match(pattern).
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.