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']]
添加回答
举报