【发布时间】:2021-03-18 10:34:51
【问题描述】:
我想使用正则表达式在字符串中只保留 3 位数字。
输入
'1 12 123 1234'
预期输出:
'123'
我厌倦了删除更多 3 位数的号码
re.sub("\d{4}", '', '1 12 123 1234')
但我不知道如何删除少于 3 位数的号码。
【问题讨论】:
-
只要使用
re.findall(r'\b\d{3,}', s) -
与其尝试删除所有位数错误的内容,不如尝试找到所有具有正确位数的内容?
-
re.findall(r"(?<!\d)\d{3}(?!\d)", s)
标签: python python-3.x regex