Substring[whole word] 使用字符串变量检查

Substring[whole word] check using a string variable

在 Python2.7 中,我正在尝试以下操作:

 >>> 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
>>>

问:使用变量 far_end_ip

时如何进行搜索

两个问题:

  • 您需要将字符串的最后一位写为正则表达式文字或转义反斜杠:... + r"\b"
  • 您应该转义文本中的点以找到:... + re.escape(far_end_ip)

所以:

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

另见 "How to use a variable inside a regular expression?"