【问题标题】:Searching for specific text in python在python中搜索特定文本
【发布时间】:2022-01-06 12:19:46
【问题描述】:

希望这是一个快速简单的方法! 我正在尝试在设备上搜索主机名,然后使用该主机名来指示通过 netmiko 发送给它的配置。 我认为我失败了,因为输出不在一条线上。 作为目前的测试,我只是尝试按如下方式打印输出:

device_name = net_connect.send_command('show running-config sys global-settings hostname')
hostname = re.search('^hostname', device_name, re.M)
print(hostname)

当我在设备上手动运行上述命令时,输出是这样的:

sys global-settings {

    hostname triton.lakes.hostname.net

}

那么我是否需要调整 re.search 以考虑单独的行以仅捕获“主机名 triton.lakes.hostname.net”行?

非常感谢

【问题讨论】:

  • ^ 不匹配,因为hostname 是缩进的(即行以空格开头)。

标签: python regex search f5 netmiko


【解决方案1】:

re

(?=...)

Matches if ... 匹配下一个,但不消耗任何字符串。这称为前瞻断言。例如,Isaac (?=Asimov) 仅在 'Asimov' 之后才会匹配 'Isaac'。

(?<=...)

如果字符串中的当前位置前面有一个在当前位置结束的 ... 匹配,则匹配。这称为肯定的后向断言。 (?

演示: (?<={).*(?=})

表示匹配以{开头并以}结尾的字符串

import re

s = """
sys global-settings {

    hostname triton.lakes.hostname.net

}
"""

print(re.search(r"(?<={)\s+(hostname .+?)\s+(?=})", s).group(1))

# hostname triton.lakes.hostname.net

【讨论】:

  • @Steve 你只需要将hostname 移出群组,像这样"(?&lt;={)\s+hostname (.+?)\s+(?=})"
  • @Steve 正如您在代码中看到的那样,我在末尾添加了一个group(1)。它的作用是取组号1匹配的数据。详细说明请参考document
  • @Steve 是正确的,这个结果说明匹配成功,是一个re.Match对象。
猜你喜欢
  • 1970-01-01
  • 2017-08-28
  • 1970-01-01
  • 2012-12-24
  • 2017-08-15
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
相关资源
最近更新 更多