python - 如何匹配字符后面出现的字符串(如果存在),否则不应匹配任何内容

标签 python regex

假设我们有以下 2 个字符串:

字符串 - 1:(完整字符串)

char = "port : id 0xa30  State INIT-DOWN (Admin Down | Port Disabled/Link status unknown)  Rate 8100  MeasuredBw 18097"

字符串 - 2:(其中部分字符串不存在。即字符串 ' Rate 8100 MeasuredBw 18097' 不存在)

char = "port : id 0xa30  State DOWN (Admin Down, Link Down, ODU Up, CCP Up)"

因此,我可以验证字符串是否存在部分字符串。但是,挑战是当字符串存在时,我无法匹配该字符串。

我想出的正则表达式(虽然不是最好的):

re.search("port\s+:\s+id\s+(\w+)\s+State\s+(\w+-*\w*)[\(\w\)\|\/\s\,]*(?:Rate\s+(\w+)\s+MeasuredBw\s+(\w+))?", port_state1).groups()

输出:

('0xa30', 'DOWN', None, None) 

对于两个字符串。

预期输出:

String-1:  
('0xa30', 'DOWN', '8100', '18097')  
String-2:  
('0xa30', 'DOWN', None, None)

最佳答案

尝试下面的模式

例如:

import re

char_1 = "port : id 0xa30 State INIT-DOWN (Admin Down | Port Disabled/Link status unknown) Rate 8100 MeasuredBw 18097"
char_2 = "port : id 0xa30 State DOWN (Admin Down, Link Down, ODU Up, CCP Up)"


print(re.search("port\s+:\s+id\s+(\w+)\s+State\s+(\w+-*\w*)\s+\(.*?\)\s*(?:Rate\s+(\d+)\s+MeasuredBw\s+(\d+))?", char_1).groups())
print(re.search("port\s+:\s+id\s+(\w+)\s+State\s+(\w+-*\w*)\s+\(.*?\)\s*(?:Rate\s+(\d+)\s+MeasuredBw\s+(\d+))?", char_2).groups())

输出:

('0xa30', 'INIT-DOWN', '8100', '18097')
('0xa30', 'DOWN', None, None)

关于python - 如何匹配字符后面出现的字符串(如果存在),否则不应匹配任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884003/

相关文章:

python - Pygame 按钮功能问题

javascript - 如何用<br>替换html正文部分中的\n字符

两个字符之间和多行之间的正则表达式

javascript - 如何从搜索中排除包含转义字符的整个单词?

javascript - 每个句子的开头大写

python - 收到 B 的正则表达式名称

python - 将方法签名延续到新行的约定

python - 如何在两个数据框中查找匹配项

python - 如何获取运算符模块的 sorted 函数来存储数据,以便我可以追加文件?

python - 如何从拟合表 python 中进行排序