Reputation: 2269
I am interested in finding any occurrence of
(somenumber)
and replacing it with
-somenumber
I have a Perl background and tried this, hoping the (\d+) grouping would populate variable $1:
myterm = re.sub(r"\((\d+)\)", "-\$1",myterm)
However this resulted in a result of the literal
-$1
How to do this in Python?
Upvotes: 1
Views: 65
Reputation: 18148
I see two problems:
You're using Perl's syntax (dollar sign) to dereference the positional match. Python uses \
, not $
.
Your backslash in "-\$1
is being interpreted by the Python compiler, and is effectively removed before re.sub
sees it.
Either using a raw string (as noted in the comments to your question), or escaping the backslash (by double-backslashing), should fix it:
myterm = re.sub(r"\((\d+)\)", r"-\1", myterm)
or
myterm = re.sub(r"\((\d+)\)", "-\\1", myterm)
Tested and confirmed:
import re
myterm = '(1234)'
# OP's attempt:
print re.sub(r"\((\d+)\)", "-\$1", myterm)
# two ways to fix:
print re.sub(r"\((\d+)\)", r"-\1", myterm)
print re.sub(r"\((\d+)\)", "-\\1", myterm)
prints:
-\$1
-1234
-1234
Upvotes: 1