I'm very new to Python, in fact this is my first script.
I'm struggling with Python's regular expressions. Specifically re.sub()
I have the following code:
variableTest = "192"
test = re.sub(r'(\$\{\d{1,2}\:)example.com(\})', r'\1' + variableTest + r'\2', searchString, re.M )
With this I'm trying to match something like host": "${9:example.com}"
within searchString
and replace example.com
with a server name or IP address.
If variableTest
contains an IP, it fails. I get the following error:
sre_constants.error: invalid group reference
I've tested it with variableTest
equal to "127.0.0.1", "1", "192", "192.168". "127.0.0.1" works while the rest doesn't. If I prepend the others with a letter it also works.
variableTest
is a string - verified with type(variableTest)
I'm totally lost as to why this is.
If I remove r'\1'
in the replacement string it also works. r'\1'
will containt ${\d}:
, with \d
a number between 1 and 999.
Any help will be greatly appreciated!
count
with the flagre.M
.