[英]Python Regex: dealing with 4 patterns using re.search() and if statement once
例如,下面是字符串列表和要返回的結果中存在的4種模式:
模式1: 'A: 45'
-> 45(45-0)
模式2: 'B: 34'
-> -34(0-34)
模式3: 'A: 45, B: 34'
-> 11(45-34)
模式4: 'B: 34, A: 45'
-> 11(45-34)
是否可以只使用一次re.search()
和一個if
語句來實現這一目標? 如果沒有,還有其他方法嗎? 非常感謝!
我想出的方法是
match = (re.search(r'(A: (\d+))?(B: (\d+))?', str))
if match:
print(float(match.group(2)) - float(match.group(4)))
它只處理前三個條件,並且會為第一個條件引發錯誤,因為match.group(2)
或match.group(4)
為NaN
。
在這里(結合了正則表達式和元組拆包):
import re
strings = ['A: 45', 'B: 34', 'A: 45, B: 34', 'B: 34, A: 45']
rx = re.compile(r'([AB]): (\d+)')
for string in strings:
groups = [m.groups() for m in rx.finditer(string)]
sum = 0
for group in groups:
(letter, value) = group
if letter == 'A':
sum += float(value)
elif letter == 'B':
sum -= float(value)
print(sum)
import re strings = ['A: 45', 'B: 34', 'A: 45, B: 34', 'B: 34, A: 45'] rx = re.compile(r'([AB]): (\\d+)') def calc(groups): sum = 0 for group in groups: (letter, value) = group c = float(value) if letter == 'A' else -float(value) sum += c return sum results = [(string, calc(groups)) \\ for string in strings \\ for groups in [rx.findall(string)]] print(results) # [('A: 45', 45.0), ('B: 34', -34.0), ('A: 45, B: 34', 11.0), ('B: 34, A: 45', 11.0)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.