Home > Software engineering >  Extract values with nested curly braces using regex in javascript
Extract values with nested curly braces using regex in javascript

Time:10-28

I have the below string in Javascript

var str = "β{;{9}/{(n-7)(n-8)}} ≤ β{;{18({3}/{2})}/{(n-8) 8} ≥ ;{36}/{9.8} ;{9}/{4}}";

I need to extract the text between curly braces starts with β symbol

i.e. β{text inside curly brases with {nested}}.

So from the above str I need to extract below two values based on β{ inside everything}

str1 = ";{9}/{(n-7)(n-8)}"`
str2 = ";{18({3}/{2})}/{(n-8) 8} ≥ ;{36}/{9.8} ;{9}/{4}"

I tried many regex examples the closest I found working is a PHP example from this stackover flow link, but its not working in Javascript.

Please help me as pattern is having PHP syntax which is failing in Javascript

\{((?:[^{}]  |\{(?1)\})  )\}

Example 1 :

 testinput = "β{test{test{12351}}{a b}{1/2}}" // Input
 testoutput = "{test{test{12351}}{a b}{1/2}}β"; // output

Example 2:

 testinput = "β{test}" // Input
 testoutput = "{test}β"; // output

CodePudding user response:

As JavaScript has no support for recursion in regex, the (?1) part of the regex is not valid (nor the double plus, but that is unrelated).

What you can do is first count the number of opening braces in the input, which gives you a ceiling on the nesting depth. Then construct a regex dynamically that supports that depth of nesting:

function extract(str) {
    const count = str.match(/(?<!β){/g)?.length ?? 0;
    const regex = RegExp("(?<=β{)[^{}]*"   "({[^{}]*".repeat(count)   "}[^{}]*)*".repeat(count)   "(?=})", "g");
    return str.match(regex);
}

var str = "β{;{9}/{(n-7)(n-8)}} ≤ β{;{18({3}/{2})}/{(n-8) 8} ≥ ;{36}/{9.8} ;{9}/{4}}";
var parts = extract(str);
console.log(parts);

  • Related