3

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]
3
  • Is the structure of the original string always the same? Commented 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. Commented 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? Commented Jul 31, 2013 at 11:10

4 Answers 4

5

Try this:

'(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)'.match(/[^(<+>)*-]+/g)
Sign up to request clarification or add additional context in comments.

3 Comments

Or even match(/[0-9a-z]+/g)
how do i understand the regex inside match??can you explain..just asking??
@MESSIAH: its matching chars that are not (<+>)*-.
5

I'd suggest:

"(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)".match(/[a-z0-9]+/g);
// ["b", "10", "c", "x", "y"]

JS Fiddle demo.

References:

Comments

3
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.

Comments

3

use regex

var pattern=/[a-zA-Z0-9]+/g
your_string.match(pattern).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.