我有一个字符串:test=' 40 virtual asset service providers law, 2020e section 1 c law 14 of 2020 page 5 cayman islands'我想匹配所有出现的数字,然后不仅打印数字,还打印数字两边的三个字符。目前,使用re我匹配的数字:print (re.findall('\d+', test ))
['40', '2020', '1', '14', '2020', '5']我希望它返回:[' 40 v', 'w, 2020e s', 'aw 14 of', 'of 2020 ', 'ge 5 c']
3 回答

浮云间
TA贡献1829条经验 获得超4个赞
干得好:
re.findall('[^0-9]{0,3}[0-9]+[^0-9]{0,3}', test)
[编辑]
打破模式:'[^0-9]{0,3}'
匹配最多 3 个非数字字符'[0-9]+'
匹配一个或多个数字
最终模式'[^0-9]{0,3}[0-9]+[^0-9]{0,3}'
匹配一个或多个数字,每边最多被 3 个非数字包围。
为了减少混淆,我赞成在模式中使用'[^0-9]{0,3}'
而不是(如其他答案中所述),因为它明确告诉需要匹配非数字。可能会造成混淆,因为它匹配任何文字(包括数字)。'.{0,3}'
'.'
添加回答
举报
0/150
提交
取消