使用 python3 中的 re.sub() 删除字符串中除给定字母后跟的数字之外的所有数字

Delete all the digits from a string except the digits that are followed by given letter using re.sub() in python3

我知道如何使用 re.sub() 从字符串中删除所有数字。但我不知道如何从字符串中删除除一些特殊数字之外的所有数字。

例如,假设我有以下字符串:

"On 11 December 2008, India entered the 3G arena"

我希望输出为:

"On December, India entered the 3G arena"

您可以使用Negative Lookahead (?!...)来确保数字后面的内容不是您设置的字母

这是一个示例,其中所有数字后跟任何字符 GJK 都不受抑制影响

import re

print(re.sub(r"\d(?![GJK])", "", "On 11 December 2008, India entered the 3G arena 1A 3J 5K"))
# On  December , India entered the 3G arena A 3J 5K

虽然 涵盖了一般情况,但这里有一个删除月份名称周围数字的解决方案:

import calendar
month_names = '|'.join([calendar.month_name[i] for i in range(1,13)])

s = "On 11 December 2008, India entered the 3G arena"

re.sub(fr"\d+\s+({month_names})\s+\d+", r"", s)
#'On December, India entered the 3G arena'

您可以使用 \b(单词边界)删除明显不是单词一部分的数字,方法如下:

import re
txt = "On 11 December 2008, India entered the 3G arena"
cleaned = re.sub(r'\b \d+\b','',txt)
print(cleaned)

输出:

On December, India entered the 3G arena

请注意,在 \d+ 之前有 space,否则您将以加倍的 space 结尾。此解决方案假定要删除的数字始终在 space 之后,如果这不成立,您可以使用 r'\b\d+\b' 然后删除 superflouos spaces.