【问题标题】:Search exact string in a file在文件中搜索确切的字符串
【发布时间】:2018-09-11 23:01:37
【问题描述】:

我正在使用下面的 if 条件和正则表达式来搜索文件中的 IP 地址,它将搜索末尾有空格的 IP 地址,例如: 192.168.x.x ,但它不搜索以 192.168.x.x/32 格式存在的 IP 地址,因为它末尾没有空格,它有一个“/”字符

如何修改搜索条件以在输出中包含两种变体

if (re.match('(.+) '  +host_ipaddress+  ' (.+)', line)):

【问题讨论】:

  • 192.168.x.x(\/\d+)? ?
  • @Dave host_ipaddress 是用户输入,我以 192.168.x.x 为例,每个八位字节的位数可以变化,例如 172.16.0.0 或 10.0.0.0

标签: python-2.7 python-2.x


【解决方案1】:
if (re.match('(.+) '  +host_ipaddress+  '(\/\d+) (.+)', line)):

if (re.match('(.+) '  +host_ipaddress+  '(\/\d{1,2}) (.+)', line)):

如果你想更精确。

尽管理想情况下,您不需要要求 (.+) 和表达式的开头或结尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2023-03-13
    • 2020-02-01
    • 2020-02-27
    • 2018-06-10
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多