Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex help in Python for selectively removing parentheses from Mathematical expressions

Tags:

python

regex

Here are some sample inputs:

x(n)+(y(n)+1)*n
x(n(a,b),a,b)+2^(y(n(a,b)+a+b)+1)
x(n)+(y(n)/(N(n)))

and I want their corresponding outputs to be:

x[n]+(y[n]+1)*n
x[n[a,b],a,b]+2^(y[n[a,b]+a+b]+1)
x[n]+(y[n]/(N[n]))

I wrote the following code, but it is not giving any output:

def replace():
    string='x(n)+2^(y(n)+1)'
    print re.sub(r'/(\w+)\(([^()]+)\)/', '\1[\2]', string)
like image 284
darkavenger Avatar asked Dec 01 '25 23:12

darkavenger


1 Answers

The PyPi regex module supports recursion. You can install it and use the following code:

>>> import regex
>>> p = regex.compile(r'\b[a-zA-Z]\w*(\((?>[^()]|(?1))*\))')
>>> s = "x(n)+(y(n)+1)*n\nx(n(a,b),a,b)+2^(y(n(a,b)+a+b)+1)\nx(n)+(y(n)/(N(n)))"
>>> print(p.sub(lambda m: m.group().replace("(", "[").replace(")", "]"), s))
x[n]+(y[n]+1)*n
x[n[a,b],a,b]+2^(y[n[a,b]+a+b]+1)
x[n]+(y[n]/(N[n]))

The regex demo is available here.

The \b[a-zA-Z]\w* matches an identifier-like sequence (a whole word starting with a letter and then followed with optional word characters (digits, letters or an underscore) and (\((?>[^()]|(?1))*\)) matches nested (...()...) sequences thanks to the subroutine call (?1) (that recurses, repeats, the pattern in Group 1).

like image 100
Wiktor Stribiżew Avatar answered Dec 03 '25 12:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!