tone7
tone7

Reputation: 355

Python re.sub() weirdness

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!

Upvotes: 6

Views: 1837

Answers (2)

nneonneo
nneonneo

Reputation: 179392

The problem is that putting an IP in variableTest will result in a replacement string like this:

r'\18.8.8.8\2'

As you can see, the first group reference is to group 18, not group 1. Hence, re complains about the invalid group reference.

In this case, you want to use the \g<n> syntax instead:

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

which produces e.g. r'\g<1>8.8.8.8\g<2>'.

Upvotes: 8

PurityLake
PurityLake

Reputation: 1120

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

This is the syntax for re.sub()

The way you seem to be calling the flag re.M, should be like flags=re.M, otherwise python will take it as if you mean that count=re.M

give it a try as it is the only thing i can decide

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

Upvotes: 1

Related Questions