我有以下字符串:
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年的年份范围内的。得到的字符串将如下所示(不要担心无关的空格):
'2014 keep this text 2015 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'发布于 2017-06-05 15:16:37
使用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)产出:
2014 keep this text 2015 2025 发布于 2017-06-05 15:09:02
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)))发布于 2017-06-05 15:00:23
我会这样做,因为它具有可读性,而且易于修复以改进:
' '.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'https://stackoverflow.com/questions/44371532
复制相似问题