1 回答

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個贊
你就快到了!您不需要三個單獨(dú)的正則表達(dá)式。相反,請?jiān)趩蝹€正則表達(dá)式中使用多個捕獲組。
(\d{3})\/(\d{2})R\s?(\d{2})
嘗試一下: https: //regex101.com/r/Xn6bry/1
解釋:
(\d{3})
:捕獲三位數(shù)字\/
: 匹配正斜杠(\d{2})
:捕獲兩位數(shù)R\s?
:匹配R
后跟一個可選的空格(\d{2})
:捕獲兩位數(shù)。
在 Python 中,執(zhí)行以下操作:
p1 = re.compile(r'(\d{3})\/(\d{2})R\s?(\d{2})')
tire = 'Tire: P275/65R18 A/S; 275/65R 18 A/T OWL;265/70R 17 A/T OWL;'
matches = re.findall(p1, tire)
現(xiàn)在如果你看一下matches,你會得到 [('275', '65', '18'), ('275', '65', '18'), ('265', '70', '17')]
將其重新排列為您想要的格式應(yīng)該非常簡單:
# Make an empty list-of-list with three entries - one per group
groups = [[], [], []]
for match in matches:
for groupnum, item in enumerate(match):
groups[groupnum].append(item)
現(xiàn)在groups是[['275', '275', '265'], ['65', '65', '70'], ['18', '18', '17']]
添加回答
舉報(bào)