Python正则表达式与“,”或字符串结尾不匹配

2024-05-16 07:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python为下面的行编写一个正则表达式来grep相应的值:

establishmentCause mo-Signalling,
Freq = 6300
Radio Bearer ID = 0, Physical Cell ID = 396

这里我想获取每个报头的值,我使用下面的正则表达式来获取值,它对除“Radio Bearer ID”之外的所有报头都成功

pat = re.compile(r'%s\s[=\s]*\b(.*)\b(?:,|\Z)'%items[i])
value = pat.search(line)
print(value.group(1))

这将"Radio Bearer ID"的输出作为0, Physical Cell ID = 396,其中我只需要0。有人能告诉我正则表达式有什么问题吗?即使我正在匹配,\Z,重新引擎在,之前不会限制匹配,但会继续。你知道吗


Tags: reidvaluecellgrepradiomofreq
2条回答

您可以使用Lookbehind和Lookahead

例如:

import re

s = """establishmentCause mo-Signalling,
Freq = 6300
Radio Bearer ID = 0, Physical Cell ID = 396"""

pat = re.compile(r'(?<=Radio Bearer ID = )(.*)(?=,)')
value = pat.search(s)
print(value.group(1))

输出:

0

量词*是贪婪的。可以使用非贪婪版本*?,或字符串结尾(\Z)之前尽可能少地匹配:

pat = re.compile(r'%s\s[=\s]*\b(.*?)\b(?:,|\Z)'%items[i])

或者,可以使用不包括,的字符类:

pat = re.compile(r'%s\s[=\s]*\b([^,]*)\b(?:,|\Z)'%items[i])

相关问题 更多 >