Regex:替换所有数字和“numberlike”字符串,范围内的年份除外

2024-09-26 22:54:09 发布

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

我有下面的绳子:

s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

我想用''替换这个字符串中包含数字的每个部分,除了1950年到2025年之间的字符串部分。结果字符串如下所示(不要担心多余的空白):

^{pr2}$

因此,实际上,我希望暴力删除远程“数字”的任何东西,除了类似于一年的独立的(即,不是另一个字符串的一部分,长度为4,不包括空格)。在

我知道我可以用这个删除所有包含数字的东西:

re.sub('\w*[0-9]\w*', '', s)

但这并不能回报我想要的:

'           keep this text        '

下面是我尝试替换与下面列出的模式不匹配的任何内容:

re.sub(r'^([A-Za-z]+|19[5-9]\d|20[0-1]\d|202[0-5])', '*', s)

返回:

'* 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

我一直在here和{a2},但找不到我要找的东西。在


Tags: 字符串textre数字this空白keep暴力
3条回答

我之所以这样做,是因为它可读性强,易于修复或改进:

' '.join(
    filter(
        lambda word: (word.isdigit() and \
                      int(word) >= 1950 and \
                      int(word) <= 2025) or \
                     re.match(r'^[a-zA-Z]+$', word),
        s.split()
    )
)
# '2014 keep this text 2015 2025'

Regex不擅长处理数字。我会抛弃regex并使用生成器表达式:

predicate= lambda w: (w.isdigit() and 1950<=int(w)<=2025) or not any(char.isdigit() for char in w)
print(' '.join(w for w in s.split() if predicate(w)))

使用re.findall()函数的短解:

s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
result = ''.join(re.findall(r'\b(19[5-9][0-9]|20[01][0-9]|202[0-5]|[a-z]+|[^0-9a-z]+)\b', s, re.I))

print(result)

输出:

^{pr2}$

相关问题 更多 >

    热门问题