正则表达式,它用NULL替换除少数单词以外的所有数字(单词可以有数字字符)

2024-09-23 10:33:57 发布

您现在位置: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

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

有什么见解吗?你知道吗


Tags: andasmatchrequirednot数字ec2单词
2条回答

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

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

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

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

此函数根据regex表达式\d+[a-zA-Z]替换给定文本中捕获的值?\函数的第二个参数是空字符串。你知道吗

输出:- 9比索ec2

一般表达式(?:(?:EXCLUDE1)|(?:EXCLUDE2)|[^\d\n])+应该解决您的问题。您可以根据需要包含任意多个非捕获组的单词或短语。你知道吗

这有点不正统,但是这个正则表达式匹配所有的东西,除了要删除的数字。至少对我来说,匹配我想要保留的文本要比删除的文本容易得多。在这种情况下,我相信python将允许您只提取匹配的文本,有效地删除数字。你知道吗

Try it here!

相关问题 更多 >