0

I'm not expert in Regex and I want just do this thing. Create this array :

["[1+5]", "1+5", "[2*[1+1]+5]", "2*[1+1]+5", "[1+1]", "1+1"]

from this string :

"blalbla[1+5] blabla [2*[1+1]+5] blalbla"

I have tested a lot of methods, I have a headache... Here the link to test what I have did: https://jsfiddle.net/a47e60pd/1/

Thanks a lot :)

4
  • If you have arbitrary level of nested brackets, you cannot use a regex. JS regex does not support recursion. Or, you may want to use XRegExp.matchRecursive. Commented Aug 28, 2016 at 20:22
  • What's the point of this exercise? Are you going to evaluate those, ie. replace 1+1 with 2? Commented Aug 28, 2016 at 20:27
  • @WiktorStribiżew Thank you for the information. Commented Aug 29, 2016 at 10:23
  • @georg Yes, then I use eval method. Oriol's answer is satisfactory answer. Commented Aug 29, 2016 at 10:25

2 Answers 2

2

Don't use regex. Just use a loop.

function* parse(str) {
  var indices = [];
  for(var i=0; i<str.length; ++i) {
    if(str[i] === '[') {
      indices.push(i);
    } else if(str[i] === ']') {
      let idx = indices.pop();
      yield str.slice(idx+1, i);
      yield str.slice(idx, i+1);
    }
  }
}
console.log([...parse("blalbla[1+5] blabla [2*[1+1]+5] blalbla")]);

Sign up to request clarification or add additional context in comments.

Comments

1

Is possible with clean regex like this:

/\[[^[]+\]|\[.+?\]([^[])+\]/g

Explanation: Group 1: \[[^[]+\] find brackets that start and finish without other brackets.

Or | Group 2:

\[.+?\] find the start of brackets, until the finish brackets, and ([^[])+\] continue find all characters that not "[" until the last "]"

var ExpToReturn;

var text = "blalbla[1+5] blabla [2*[1+1]+5] blalbla";

var str = text.match(/\[[^[]+\]|\[.+?\]([^[])+\]/g);

ExpToReturn = (str);

alert (ExpToReturn);

1 Comment

Your method is also good. But I prefer Oriol's method. Thanks a lot for your useful answer

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.