0

In Python2.7, I am trying the following:

 >>> import re
>>> text='0.0.0.0/0 172.36.128.214'
>>> far_end_ip="172.36.128.214"
>>>
>>>
>>> chk=re.search(r"\b172.36.128.214\b",text)
>>> chk
<_sre.SRE_Match object at 0x0000000002349578>
>>> chk=re.search(r"\b172.36.128.21\b",text)
>>> chk
>>> chk=re.search(r"\b"+far_end_ip+"\b",text)
>>>
>>> chk
>>>

Q:how can i make the search work when using the variable far_end_ip

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
fsociety
  • 977
  • 3
  • 12
  • 23

1 Answers1

1

Two issues:

  • You need to write the last bit of the string as a regex literal or escape the backslash: ... + r"\b"
  • You should escape the dots in the text to find: ... + re.escape(far_end_ip)

So:

re.search(r"\b" + re.escape(far_end_ip) + r"\b",text)

See also "How to use a variable inside a regular expression?".

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286