Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re.sub "(-)" failed

Tags:

python

string

I am not able to replace the string "(-)" using re.sub in Python.

>>> instr = 'Hello, this is my instring'
>>> re.sub('my', 'your', instr)
'Hello, this is your instring'
>>> instr = 'Hello, this is my (-) instring'
>>> re.sub('my (-)', 'your', instr)
'Hello, this is my (-) instring'

Can somebody please give me a hint what I am doing wrong.

Thank you!

like image 946
Tim Avatar asked May 07 '26 17:05

Tim


2 Answers

re.sub(r'my \(-\)', 'your', instr)

You have to escape the parenthesis, which are normally used for matching groups. Also, add an r in front of the string to keep it raw (because of backslashes).

Or don't use regexp at all (if your substitution is that simple) and you don't have to care about many issues:

>>> instr = 'Hello, this is my (-) instring'
>>> instr.replace('my (-)', 'your')
'Hello, this is your instring'
like image 137
eumiro Avatar answered May 10 '26 08:05

eumiro


You need to escape the '(-)' because it is a regular expression pattern match, as far as the regex engine is concerned. If you're not sure about how to escape, but your string doesn't have any actual patterns but should be interpreted verbatim, you should do:

>>> re.sub(re.escape('my (-)'), 'your', instr)
'Hello, this is your instring'

or if your string is a mix between a "plain" pattern and complex stuff, you can do this:

>>> re.sub('[a-z]{2} %s' % re.escape('(-)'), 'your', instr)
'Hello, this is your instring'
like image 26
Not_a_Golfer Avatar answered May 10 '26 06:05

Not_a_Golfer



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!