假设我们有以下 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/