首页 > 解决方案 > 正则表达式按数字匹配组

问题描述

import re
digits = '122223444'

预期的:

['1', '2222', '3','444']

标签: pythonregex

解决方案


您可以使用捕获组和反向引用

(\d)\1*

在此处输入图像描述

Regex Demo |Python demo


import re
regex = r"(\d)\1*"  
test_str = "122223444"
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

推荐阅读