在 python 中搜索特定文本

Searching for specific text in python

希望这是一个快速简单的操作! 我正在尝试在设备上搜索主机名,然后使用该主机名来指示通过 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 以考虑单独的行以仅捕获 'hostname triton.lakes.hostname.net' 行?

非常感谢

re

(?=...)

Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

(?<=...)

Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in 'abcdef', since the lookbehind will back up 3 characters and check if the contained pattern matches.

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

It means to match strings beginning with { and ending with }

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