remove empty parenthesis from expression

Viewed 224

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 ?

4 Answers

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);
}

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.

You can use /\(\s*\)/ to remove unnested pairs:

  • Escape the parentheses using \( and \) because they have a special meaning in regexps.
  • Allow zero or more whitespace characters instead of just one, using \s*.

However, you cannot remove nested parentheses this way using a truly regular expression, as a consequence of the pumping lemma. Regexps in JavaScript aren't "regular" expressions in the theoretical sense, so maybe something can be done (for example with backreferences), but I don't immediately see it.

One possible solution is to repeatedly apply the above regexp until the string no longer changes.

This example run for me:

let expression1 = "( (  (  ()  )  )a and b)"

let last_expression1 = ""
let regex = /(\(\ *\))+/g;
while (expression1 != last_expression1) {
  last_expression1 = expression1
  expression1 = expression1.replace (regex, '')
}

console.log(expression1)

The correct regex is:

/(\(\ *\))+/g
Related