正则表达式Python - 将任何换行符、制表符、空格的组合替换为单个空格。

5
我正在尝试找到一个正则表达式,可以将所有换行符和制表符(\n, \r, \t等)以及前、后、中间的任何空格都替换为一个空格。例如,字符串:
'Copyright ©\n\t\t\t\n\t\t\t2019\n\t\t\tApple Inc. All rights reserved.'
应该变成:
'Copyright © 2019 Apple Inc. All rights reserved.'
在原始字符串是这种情况时:
'Copyright © \n\t \t\t\n \t\t\t2019\n\t\t\t Apple Inc. All rights reserved.'
最终结果应该相同。
对于单个换行符,在最简单的情况下,如果没有额外的空格,它会像这样:
re.sub(r"\n", " ", html)

但是由于我不经常处理正则表达式,所以我不知道如何解决我需要的问题。


你不需要使用正则表达式。' '.join('版权 ©\n\t\t\t\n\t\t\t2019\n\t\t\tApple Inc. 保留所有权利。'.split()) 将会给你想要的输出结果。 - BoarGules
1个回答

16
尝试使用\s,它匹配所有空白字符。
>>> import re
>>> s = 'Copyright ©\n\t\t\t\n\t\t\t2019\n\t\t\tApple Inc. All rights reserved.'
>>> s = re.sub("\s+", " ", s)
>>> s
'Copyright © 2019 Apple Inc. All rights reserved.'

你甚至可以在'\s'之后省略'+'符号。 - SBylemans
2
re.sub("\s", " ", s) 会将所有制表符、换行符等替换为空格。但它会用相同数量的空格替换连续的空白字符。如果你想让 "\t\t\t" 变成一个空格,那么最好使用 re.sub("\s+", " ", s) - Kevin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接