Python,regex排除匹配的数字

2024-10-01 15:48:33 发布

您现在位置:Python中文网/ 问答频道 /正文

要使用regex在字符串中提取长度大于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的最后评论以获取更新。


Tags: 字符串importreidstringemployee数字year
3条回答

另一种方法是:

st="Employee ID DF856, Year 2016, Department Finance, Team 2, Location 112 "
re.findall(r"\d{3,}",re.sub("((2)?(016))","",st))

输出为:

['856', '112']

但我看到的公认答案比我的建议更快。你知道吗

你可以用

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 demoregex demo。你知道吗

细节

  • (?<!\d)-当前位置左侧不允许有数字
  • (?!2016(?!\d))-no2016当前位置的右边不允许紧跟另一个数字
  • \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。你知道吗

你想用消极的前瞻。正确的语法是:

\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']

相关问题 更多 >

    热门问题