如何用正则表达式解释字符串?

2024-06-02 07:35:33 发布

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

我正在使用一个数据字符串,需要对该字符串进行解释,才能从“LpA:45dB typical,48db max”中获得键值“45dB typical,48db max”。你知道吗

我尝试使用正则表达式模式'(.*)LpA:(\w*)\n解决问题


data_str="""With AC power supply (with 24 PoE+ ports loaded for C9300 SKUs)
●  LpA: 45dB typical, 48 dB max
●  LwA: 5.6B typical, 5.9B max
With AC power supply (with half the number of PoE+ ports loaded for C9300L SKUs)
●  LpA: 44dB typical, 47 dB max
●  LwA: 5.5B typical, 5.8B max
Typical: Noise emission for a typical configuration
Maximum: Statistical maximum to account for variation in production"""

pattern_type=re.compile('(.*)LpA:(\w*)\n',re.I)
key = pattern_type.sub(r"\2","%r"%data_str)
print(key)


我希望:
''典型45dB,最大48dB''
但我们要做的是:
''典型45dB,最大48dB ●LwA:5.6B典型值,5.9B最大值 带交流电源(为C9300L SKU加载一半PoE+端口) ●LpA:典型44 dB,最大47 dB ●LwA:5.5B典型值,5.8B最大值 典型:典型配置的噪声发射 最大值:用于说明产量“”变化的统计最大值


Tags: 字符串fordbdatawithmaxacpower
3条回答

只需使用一个积极的回顾:

(?<=LpA: ).+$

Regex Demo

说明:

(?<=LpA: )   Assert that matching LpA, but do not capture in final match
.+           Capture any character
$            Till end of line

代码段:

regex = re.compile("(?<=LpA: ).+$", re.M)
for match in regex.findall(*your_string_here*):
    print(match)

这应该起作用:

res = re.search('LpA:(.*)\n', data_str)
if res: #if res is not None
    key = res.group(1).strip()
    print(key)

似乎您试图匹配整个字符串,然后用其中一个匹配组替换它。相反,只需使用re.search来获得匹配的组。另外,您可能希望使用.而不是\w,因为子字符串包含空格和其他非单词字符。你知道吗

>>> pattern_type = re.compile('LpA: (.*)')
>>> key = pattern_type.search(data_str)
>>> key.group(1)
45dB typical, 48 dB max

相关问题 更多 >