1 回答

TA貢獻1788條經驗 獲得超4個贊
你就快到了!您不需要三個單獨的正則表達式。相反,請在單個正則表達式中使用多個捕獲組。
(\d{3})\/(\d{2})R\s?(\d{2})
嘗試一下: https: //regex101.com/r/Xn6bry/1
解釋:
(\d{3})
:捕獲三位數字\/
: 匹配正斜杠(\d{2})
:捕獲兩位數R\s?
:匹配R
后跟一個可選的空格(\d{2})
:捕獲兩位數。
在 Python 中,執行以下操作:
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)
現在如果你看一下matches,你會得到 [('275', '65', '18'), ('275', '65', '18'), ('265', '70', '17')]
將其重新排列為您想要的格式應該非常簡單:
# 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)
現在groups是[['275', '275', '265'], ['65', '65', '70'], ['18', '18', '17']]
添加回答
舉報