如果其他字符不匹配任何字符,如何匹配字符后面的字符串

时间:2019-02-26 11:01:24

标签: python python-2.7 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) for both the string.

预期输出:

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

1 个答案:

答案 0 :(得分:0)

尝试以下模式

例如:

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)