Substring[whole word] check using a string variable

151 views Asked by At

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

1

There are 1 answers

0
trincot On BEST ANSWER

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?".