0
p = re.compile('Dhcp Server .*? add scope .*? (.*?) ')
test_str = 'Dhcp Server \\server1 add scope 10.0.1.0 255.255.255.0 "area1"'
subst = "255.255.254.0"
re.sub(p, subst, test_str)

The output is 255.255.254.0. What i am trying to get is this:

Dhcp Server \\server1 add scope 10.0.1.0 255.255.254.0 "area1"'

I can't simply use string replace because server1 and 10.0.1.0 will by dynamic.

How can I get my desired result when using Python 3.5? I looked at other SO questions, but did not find one quite like my question.

0

3 Answers 3

2

You can use capturing groups for this:

test_str = 'Dhcp Server \\server1 add scope 10.0.1.0 255.255.255.0 "area1"'

print re.sub(r'(Dhcp Server .*? add scope [\d.]+) [\d.]+ (.*)', r"\1 255.255.254.0 \2", test_str)

We are capturing text before replacement position into \1 and part after replacement is available in \2.

Output:

Dhcp Server \\server1 add scope 10.0.1.0 255.255.254.0 "area1"
Sign up to request clarification or add additional context in comments.

Comments

1

You have it backwards. You use capture groups for the parts of the expression that you want to copy, not the parts you want to replace. Then you use a back-reference in the replacement string to copy them.

p = re.compile('(Dhcp Server .*? add scope .*? ).*? ')
test_str = 'Dhcp Server \\server1 add scope 10.0.1.0 255.255.255.0 "area1"'
subst = r"\g<1>255.255.254.0 "
re.sub(p, subst, test_str)

4 Comments

This returns: 'U5.255.254.0 "area1"'
Need to use \g<1> because it was looking for group number 125.
Can you please explain what is meant by "group number 125"?
When backslash is followed by a number, it means to substitute that capture group. My original answer had \1255.255.254.0 in the replacement, so it treated \125 as a back-reference to group number 125.
1

Or you could just match the parts you want and then reconstruct the line (particularly if you want to know if you have made a replacement):

p = re.compile('(Dhcp Server .*? add scope .*? )(.*?)( .*)')
test_str = 'Dhcp Server \\server1 add scope 10.0.1.0 255.255.255.0 "area1"'
subst = "255.255.254.0"
match = p.match(test_str)
if match:
  replaced = match.group(1) + subst + match.group(3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.