Python re regex sub letters not surrounded in quotes and not if they match specific word including regex group / match

Viewed 87

I need to sub letters not surrounded in quotes and not if they match the word TODAY with a particular string where a part of it includes the match group e.g.

import re
import string

s = 'AB+B+" HELLO"+TODAY()/C* 100'
x = re.sub(r'\"[^"]*\"|\bTODAY\b|([A-Z]+)', r'a2num("\g<0>")', s)

print (x)

expected output:

'a2num("AB")+a2num("B")+" HELLO"+TODAY()/a2num("C")* 100'

actual output:

'a2num("AB")+a2num("B")+a2num("" HELLO"")+a2num("TODAY")()/a2num("C")* 100'

I am nearly there but it is not obeying the quote rules or the TODAY word rule, I know the string doesn't make any sense but it's just a harsh test of the regex

1 Answers

Your regex approach is correct but you need to use a lambda function in re.sub

>>> s = 'AB+B+" HELLO"+TODAY()/C* 100'
>>> rs = re.sub(r'"[^"]*"|\bTODAY\b|\b([A-Z]+)\b',
...     lambda m: 'a2num("' + m.group(1) + '")' if m.group(1) else m.group(), s)
>>> print (rs)

a2num("AB")+a2num("B")+" HELLO"+TODAY()/a2num("C")* 100

Code Demo

Related