在关键字后打印第一个单词

问题描述 投票:0回答:2

我想得到指定关键字'dataplane'之后的第一个单词

output = 'set interfaces dataplane dp0p1 vif 2129 description '*** WAN - Global ***''

我想得到数据平面后的单词dp0p1

python python-3.x
2个回答
0
投票

假设您想输入多个关键字,并假设dataplane应该出现多次,则可以在此处使用re.findall

output = 'set interfaces dataplane dp0p1 vif 2129 description '
matches = re.findall('\\bdataplane (\S+)', output)
print(matches)

此打印:

['dp0p1']

0
投票

[假设您不可能使用多个关键字,并且假设dataplane出现一次,则可以在此处使用next

output = 'set interfaces dataplane dp0p1 vif 2129 description'

splitted = output.split()
print(next((y for x, y in zip(splitted, splitted[1:]) if x == 'dataplane'), ''))

此打印:

dp0p1
© www.soinside.com 2019 - 2024. All rights reserved.