首页 > 解决方案 > 正则表达式,用 NULL 替换所有数字,除了几个单词(单词可以有数字字符)

问题描述

用空字符串替换所有数字的正则表达式,除了几个单词(单词可以有数字字符)——python 例如要排除的单词:“cloud9”和“ec2”

cloud9 100 pesos dollars99 908908f098080 800 ec2

应转换为:

cloud9  pesos dollars f  ec2

在python中试过这个:

    \b(?!ignoreme23|43ignoreyou)\b\d+

测试上述表达式:

8 --> matches 8

8u9 --> matches 8 but not 9

100f --> matches 100

f100 --> does not match anything

999 --> matches all 9s

ignoreme23 --> ignores as required

ignoreme232323 --> ignores "ignoreme23" but does not match with the following "2323"

2434ignoreme23 --> matches 2334 ignores "ignoreme23" as required

23243ignoreyou --> matches 23243. Should only match 2324 and should ignore "43ignoreyou"

232 43ignoreyou --> matches 232 and ignores "43ignoreyou" as required

43ignoreyou --> ignores as required

尝试了不同的正则表达式,但似乎无法解决这个问题。

有什么见解吗?

标签: pythonregexregex-lookaroundsregex-negationregexp-replace

解决方案


你可以试试这个简单的正则表达式

\d+[a-zA-Z]?\d+

要替换给定文本中的数字,请应用以下内容

re.sub(r'\d+[a-zA-Z]?\d+', '', giventext)

此函数根据正则表达式 \d+[a-zA-Z]?\d+ 将给定文本中的捕获值替换为函数的第二个参数,该参数是一个空字符串。

输出:- cloud9 比索美元 ec2


推荐阅读