简体   繁体   中英

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:

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"

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 . 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.

Quantifier * is greedy. You can use the non-greedy version *? to match as little as possible before the , or end of string ( \\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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM