Skip to content
Advertisement

Substitude everything in “()” but ignore those cases where round brackects are inside square brackets “” in regrex

Hi I am trying to use regrex to replace everything surounded by “()” with an empty string “”, but not in the case where “()” is in an angle bracket. e.g. “<..()>” should be ignored and not replaced. Example input:

JavaScript

Example output:

JavaScript

Following what I read from answer

I have tried using the following method:

JavaScript

But it instead outputted

JavaScript

Can anyone explain what might have gone wrong?

Advertisement

Answer

You have wrapped the wrong alternative with a capturing group and missed the backreference in the replacement part:

JavaScript

See the Python demo.

Note the < and > are not special chars, and need not escaping.

The (<[^<>]*>)|([^()]*) pattern captures into Group 1 any substring that starts with <, then has zero or more chars other than < and > and then ends with >, and just matches any substring between ( and ) having no other ( and ) in between.

The 1 replacement puts back the captured substring where it was.

Advertisement