[英]Python regex not matching for “,” or end of string
I want to write a single regular expression in python for below lines to grep the corresponding values: 我想在python中为以下行编写一个正则表达式,以grep相应的值:
establishmentCause mo-Signalling,
Freq = 6300
Radio Bearer ID = 0, Physical Cell ID = 396
Here i want to fetch the values for each header, I am using the below regular expression to fetch values and it succeeds for all except "Radio Bearer ID" 在这里,我想获取每个标头的值,我使用下面的正则表达式来获取值,并且除“ Radio Bearer ID”外,所有内容都成功
pat = re.compile(r'%s\s[=\s]*\b(.*)\b(?:,|\Z)'%items[i])
value = pat.search(line)
print(value.group(1))
This gives the output for "Radio Bearer ID"
as 0, Physical Cell ID = 396
where as I want only 0
. 这将
"Radio Bearer ID"
的输出设置为0, Physical Cell ID = 396
,其中我只希望0
。 Can some one please tell me what the problem is with my regular expression even though I am matching ,
and \\Z
the re engine dose not limit the match till ,
but continues further. 即使我正在匹配
,
也可以有人告诉我我的正则表达式出了什么问题,
并且\\Z
重新启动引擎不会将匹配限制到,
而是继续。
Quantifier *
is greedy. 量词
*
是贪婪的。 You can use the non-greedy version *?
您可以使用非贪婪版本
*?
to match as little as possible before the ,
or end of string ( \\Z
): 到之前尽量少匹配
,
或串(的端\\Z
):
pat = re.compile(r'%s\s[=\s]*\b(.*?)\b(?:,|\Z)'%items[i])
Alternatively, you can use a character class excluding ,
instead: 或者,你可以使用一个字符类除外
,
而不是:
pat = re.compile(r'%s\s[=\s]*\b([^,]*)\b(?:,|\Z)'%items[i])
You can use Lookbehind & Lookahead 您可以使用Lookbehind和Lookahead
Ex: 例如:
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))
Output: 输出:
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.