asosnovsky
asosnovsky

Reputation: 2235

Regex: How to return matches that are not in the bracket

So I technically already solved this issue, but I was hoping for a better solution using some funky regex.

The issue is: We got strings this:

2+{2+(2)},

10+(20+2)+2

The goal is to match the 'plus' signs that are not in any sort of bracket. i.e. in the previous strings it should match

2 + {2+(2)} ,

10 + (20+2) + 2

at the moment what I am doing is matching all plus signs, and then checking to see if the sign has any bracket in front of it (using regex), if it does then get rid of it.

I was hoping for a neater regex solution, is that possible?

To reiterate, I need the location of the strings, at the moment I am using javascript to do this, so ideally a js solution is preferred, but the pattern is really what I am looking for.

Upvotes: 0

Views: 47

Answers (1)

BrunoLM
BrunoLM

Reputation: 100331

You could perhaps just replace everything inside () or {} with spaces:

'10 + (20+2) + 2'.replace(/\([^)]*?\)|\{[^}]*?\}/g, m => ' '.repeat(m.length));

This would result in

10 +        + 2

Meaning the position of the strings aren't changed.

Note: It won't work well with nested things of the same type, ex (1 + (1 + 1) + 1), but it works with (1 + { 1 + 1 } + 1).


Bigger solution, using the same logic, but that works with nested stuff

var input = '10 + { 1 + (20 + (1 + { 3 + 3 } + 1) + 2) + 2 }';

var result = [];
var opens = 0;
for (var i = 0; i < input.length; ++i) {
  var ch = input[i];
  if (/\(|\{/.test(ch)) {
    opens++;
    result[i] = ' ';
  }
  else if (/\)|\}/.test(ch)) {
    opens--;
    result[i] = ' ';
  }
  else {
    if (!opens) result[i] = input[i];
    else result[i] = ' ';
  }
}

result = result.join('');
// "10 +                                           "

Upvotes: 1

Related Questions