我有下面的绳子:
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年之间的字符串部分。结果字符串如下所示(不要担心多余的空白):
因此,实际上,我希望暴力删除远程“数字”的任何东西,除了类似于一年的独立的(即,不是另一个字符串的一部分,长度为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},但找不到我要找的东西。在
我之所以这样做,是因为它可读性强,易于修复或改进:
Regex不擅长处理数字。我会抛弃regex并使用生成器表达式:
使用
re.findall()
函数的短解:输出:
^{pr2}$相关问题 更多 >
编程相关推荐