regex - JavaScript - RegExp - Replace useless parentheses in string -
so have string this, ready evaluated:
"getinfo(((((2+2)*(3/4) / ((44))))))"
so, there's 1 place tripple parenthese is useless , 1 place double 1 useless, string can simplyfied this:
"getinfo((2+2)*(3/4) / (44))"
in order sort these unnesseccary parentheses out can replace every 2 useless parentheses 1 parenthese, this:
"do((((2+2 - 3)*(2))))" -> "do(((2+2 - 3)*(2)))" -> "do((2+2 - 3)*(2))"
is there anyway either regexp or looping using string.replace method this, , how?
this seems work:
function simplify(str) { var i=0; homecoming (function recur(s, b) { var c = str.charat(i++); // next char if(!c || c == ')') homecoming s; // end of string or end of inner part if(c == '(') { var s1 = recur('', true), // inner part s2 = recur(''); // next part homecoming s + (!b || s2 ? '('+s1+')' : s1) + s2; } homecoming recur(s+c); // go on next char })(''); }
this code should equivalent, less function calls:
function simplify(str) { var i=0; homecoming (function recur(b) { var c, s = ''; while(c = str.charat(i++)) { // maintain getting chars if(c == ')') homecoming s; // end of inner part if(c == '(') { var s1 = recur(true), // inner part s2 = recur(); // next part homecoming s + (!b || s2 ? '('+s1+')' : s1) + s2; } s += c; // add together current char b = false; } homecoming s; })(); }
the part gets rid of unnecessary parentheses one:
return s + (!b || s2 ? '('+s1+')' : s1) + s2;
basically, returns current string, concatenated inner part (maybe parenthesized), concatenated next part.
the inner part parenthesized either if next part not empty, or if b
falsy (that is, if inner part not wrapped in parentheses).
note codes above expect well-formed expression. if not,
the returned string truncated if there )
without corresponding (
simplify("a)b"); // "a"
the returned string have additional )
@ end if there unclosed (
:
simplify("a(b"); // "a(b)"
javascript regex string
No comments:
Post a Comment