1

I need to detect that brackets of different type were properly opened and closed in a string. For instance:

  • "(){}[]" --> true.
  • "[][{](})" --> false

I did a try but can't deal with the "false" case:

/(\{+\})|(\(+\))|(\[+\])|^$/.test("[][{](})");

Any idea?

Ryszard Czech
  • 10,599
  • 2
  • 12
  • 31
gal007
  • 5,504
  • 5
  • 35
  • 58
  • 1
    Do you *HAVE* to do this with regex? – VLAZ Nov 16 '20 at 19:48
  • Yes, I have to :) – gal007 Nov 16 '20 at 19:52
  • 3
    You can't detect recursive structures via a single regex. – Ouroborus Nov 16 '20 at 19:53
  • 2
    [Regular expression to match balanced parentheses](https://stackoverflow.com/q/546433) | [Using RegEx to balance match parenthesis](https://stackoverflow.com/q/7898310) – VLAZ Nov 16 '20 at 19:54
  • 2
    If you can apply the same regex repeatedly, you can find and remove every immediately adjacent opening and closing element: `/{}|\[\]|\(\)/`. Once you can't find any more of these, check if the string still has anything in it. If it does, then it has mismatched brackets. – Ouroborus Nov 16 '20 at 20:04

1 Answers1

1

Use

const strings = ["(){}[]", "[][{](})"];
const regex = /\(\)|\[]|{}/g;
strings.forEach(x => { 
  let t = x;
  while (t.match(regex)) t = t.replace(regex, '');
  console.log(x, '=>', t.length == 0);
});

Remove all {}, [] and () if present, check if the string length is 0 or not when there are no more matches.

Ryszard Czech
  • 10,599
  • 2
  • 12
  • 31