0

I was trying to make a node's program that takes a string, and gets all of the content inside it:

var str = "Hello {world}!";

console.log(getBracketSubstrings(str)); // => ['world']

It works, but when I do:

var str = "Hello {world{!}}";
console.log(getBracketSubstrings(str)); // => ['world{!']

It returns ['world{!}'], when I want it to return:

['world{!}']

Is there anyway to do this to a string in nodes?

darkdarcool
  • 43
  • 2
  • 8

1 Answers1

0

You could use a pattern with a capture group, matching from { followed by any char except a closing curly using [^}]* until you encounter a }

{([^}]*)}

See a regex demo

const getBracketSubstrings = s => Array.from(s.matchAll(/{([^}]*)}/g), x => x[1]);
console.log(getBracketSubstrings("Hello {world}!"));
console.log(getBracketSubstrings("Hello {world{!}}"));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • This is good, but is there a way to get the final }? – darkdarcool Jul 28 '21 at 11:03
  • @user14929391 Like this? `{([^{}]+(?:{[^{}]*})?)}` https://regex101.com/r/GZJaWH/1 – The fourth bird Jul 28 '21 at 11:07
  • That works great, and sorry to bother you again, but it doesn’t seem to work if there is more than one bracket substring in another bracket substring, is that possible? If not, that’s fine – darkdarcool Jul 28 '21 at 11:34
  • Then you have to match [balanced parenthesis](https://stackoverflow.com/questions/546433/regular-expression-to-match-balanced-parentheses?answertab=votes#tab-top) Javascript regex does not support recursion. – The fourth bird Jul 28 '21 at 11:37