Python Regex - Replace Single Quotes And Brackets
I'd like to replace quantities with name then a square bracket and a single quote with the contents inside. So, from this: RSQ(name['BAKD DK'], name['A DKJ']) to this: RSQ(BAKD DK
Solution 1:
Code -
import re
s = "RSQ(name['BAKD DK'], name['A DKJ'])"
expr = r"[\'\[\]]|\bname\b"print(re.sub(expr, '', s))
Output -
RSQ(BAKD DK, A DKJ)
Solution 2:
You can also use the saving groups to extract strings from inside the name['something']
:
>>>import re>>>s = "RSQ(name['BAKD DK'], name['A DKJ'])">>>re.sub(r"name\['(.*?)'\]", r"\1", s)
'RSQ(BAKD DK, A DKJ)'
where (.*?)
is a capturing group that would match any characters any number of times in a non-greedy fashion. \1
references the captured group in a replacement string.
Post a Comment for "Python Regex - Replace Single Quotes And Brackets"