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]
asked Jul 31, 2013 at 11:04
Jetson John
3,8298 gold badges42 silver badges53 bronze badges
-
Is the structure of the original string always the same?StackFlower– StackFlower2013年07月31日 11:08:26 +00:00Commented Jul 31, 2013 at 11:08
-
I suggest reading about the XY Problem. It would be interesting to see more about the actual problem you're trying to solve here. It looks like you're trying to write a parsing engine? Perhaps if you expand a bit on that, you might get more answers that are actually useful rather than directly solving the sub-problem you've posed in the question currently.Spudley– Spudley2013年07月31日 11:08:43 +00:00Commented Jul 31, 2013 at 11:08
-
Can I ask where is that string coming from, and what is the intended purpose of the angle-brackets?David Thomas– David Thomas2013年07月31日 11:10:58 +00:00Commented Jul 31, 2013 at 11:10
4 Answers 4
Try this:
'(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)'.match(/[^(<+>)*-]+/g)
answered Jul 31, 2013 at 11:07
CD..
74.4k25 gold badges160 silver badges170 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Benubird
Or even
match(/[0-9a-z]+/g)HIRA THAKUR
how do i understand the regex inside match??can you explain..just asking??
CD..
@MESSIAH: its matching chars that are not
(<+>)*-.I'd suggest:
"(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)".match(/[a-z0-9]+/g);
// ["b", "10", "c", "x", "y"]
References:
answered Jul 31, 2013 at 11:06
David Thomas
254k53 gold badges382 silver badges421 bronze badges
Comments
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.
answered Jul 31, 2013 at 11:09
poke
392k80 gold badges596 silver badges632 bronze badges
Comments
use regex
var pattern=/[a-zA-Z0-9]+/g
your_string.match(pattern).
answered Jul 31, 2013 at 11:09
Lonely
6133 gold badges6 silver badges14 bronze badges
Comments
lang-js