Python re.sub () weirdness

I am very new to Python, this is actually my first script.

I am struggling with Python regular expressions. In particular 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 am trying to match something like host": "${9:example.com}" inside searchString and replace example.com with the server name or IP address.

If variableTest contains an IP, it fails. I get the following error: sre_constants.error: invalid group reference

I tested it with variableTest equal to "127.0.0.1", "1", "192", "192.168". "127.0.0.1" works, but the rest does not. If I add another letter, it also works.

variableTest is a string - checked with type(variableTest)

I completely lost why this is so.

If I delete r'\1' in the replacement string, it also works. r'\1' will contain t ${\d}: with \d number from 1 to 999.

Any help would be greatly appreciated!

+6
source share
2 answers

The problem is that including the IP address in variableTest will replace the string as follows:

 r'\18.8.8.8\2' 

As you can see, the first link to the group refers to group 18, and not to group 1. Therefore, re complains about the invalid link to the group.

In this case, instead of \g<n> syntax should be used

 r'\g<1>' + variableTest + r'\g<2>' 

which produces, for example, r'\g<1>8.8.8.8\g<2>' .

+8
source

re.sub (pattern, repl, string, count = 0, flags = 0)

This is the syntax for re.sub ()

The way you seem to call the re.M flag should look like flags = re.M, otherwise python will treat it as if you meant that count = re.M

try as this is the only thing i can solve

also give me an example of what your searchString variable might contain

+1
source

All Articles