要使用正则表达式在字符串中提取任何长度大于 2 的数字,但还要排除“2016”,这是我所拥有的:import restring = "Employee ID DF856, Year 2016, Department Finance, Team 2, Location 112 "print re.findall(r'\d{3,}', string)输出:['856', '2016', '112']我试图将其更改为以下以排除“2016”,但都失败了。print re.findall(r'\d{3,}/^(!2016)/', string)print re.findall(r"\d{3,}/?!2016/", string)print re.findall(r"\d{3,}!'2016'", string)正确的做法是什么?谢谢你。
3 回答
![?](http://img1.sycdn.imooc.com/545865890001495702200220-100-100.jpg)
慕桂英3389331
TA贡献2036条经验 获得超8个赞
您可以使用
import re
s = "Employee ID DF856, Year 2016, Department Finance, Team 2, Location 112 20161 12016 120162"
print(re.findall(r'(?<!\d)(?!2016(?!\d))\d{3,}', s))
细节
(?<!\d)
- 当前位置左侧不允许有任何数字(?!2016(?!\d))
-2016
在当前位置的右侧不允许紧跟另一个数字\d{3,}
- 3 位或更多位数字。
带有一些代码的替代解决方案:
import re
s = "Employee ID DF856, Year 2016, Department Finance, Team 2, Location 112 20161 12016 120162"
print([x for x in re.findall(r'\d{3,}', s) if x != "2016"])
在这里,我们提取任何 3 个或更多数字 ( re.findall(r'\d{3,}', s)) 的块,然后过滤掉那些等于2016。
![?](http://img1.sycdn.imooc.com/5333a2320001acdd02000200-100-100.jpg)
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
您想使用负前瞻。正确的语法是:
\D(?!2016)(\d{3,})\b
结果是:
In [24]: re.findall(r'\D(?!2016)(\d{3,})\b', string) Out[24]: ['856', '112']
或者使用负面回顾:
In [26]: re.findall(r'\D(\d{3,})(?<!2016)\b', string) Out[26]: ['856', '112']
添加回答
举报
0/150
提交
取消