Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove empty parenthesis from expression

I want to remove those parenthesis which are empty from expression in javascript regular expression. For e.g (() a and b) -> ( and b). It should also work for the case ( ( ( () ) )a and b) -> (a and b). Basicaly it should remove unnecessary parenthesis from expression. I am writng reguar expression

expression.replace(/(\s)/,'');   

but this is not working. Can anyone help ?

like image 339
user1887464 Avatar asked Oct 24 '25 04:10

user1887464


2 Answers

You can use

const text = "( (  (  ()  )  )a and b)";
let output = text;
while (output != (output = output.replace(/\(\s*\)/g, ""))); 
console.log(output); 

The /\(\s*\)/g regex matches all non-overlapping occurrences of

  • \( - a literal ( char
  • \s* - zero or more whitespace chars
  • \) - a literal ) char.

The while (output != ...) loop makes sure the replacement occurs as many times as necessary to remove all substrings between open/close parentheses until no more matches are found.

like image 75
Wiktor Stribiżew Avatar answered Oct 25 '25 18:10

Wiktor Stribiżew


There are different ways to do this, a simple, iterative one is to repeatedly remove emtpy parentheses (need to be escaped in regex!):

function remove_empty_parens(str) {
    let new_str = str.replace(/\(\s*\)/, '');
    return new_str == str ? str : remove_empty_parens(new_str);
}
like image 30
The Coprolal Avatar answered Oct 25 '25 16:10

The Coprolal