要使用正则表达式在字符串中提取任何长度大于 2 的数字,但还要排除“2016”,这就是我所拥有的:
import re
string = "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)
正确的做法是什么?谢谢。
问题已扩展,请参阅 Wiktor Stribiżew 对更新的最后评论。
请您参考如下方法:
你可以使用
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))
参见 Python demo和一个 regex demo .
详情
-
(?<!\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 位或更多位数字的 block (re.findall(r'\d{3,}', s)),然后过滤掉等于 2016 的那些.
