首页 > 解决方案 > 正则表达式 Python - 用单个空格替换换行符、制表符、空格的任意组合

问题描述

我正在尝试找到一个常规 exp,它使我能够用一个空格替换所有换行符和制表符(\n、\r、\t 等),以及之前、之后和中间的任何空格。例如,字符串

'版权所有 ©\n\t\t\t\n\t\t\t2019\n\t\t\tApple Inc. 保留所有权利。'

应该变成

“版权所有 © 2019 Apple Inc. 保留所有权利。”

此外,如果原始字符串是:

'版权 © \n\t \t\t\n \t\t\t2019\n\t\t\t Apple Inc. 保留所有权利。'

最后的结果应该是一样的。

对于单个换行符,在没有额外空格的最简单情况下,它会类似于

re.sub(r"\n", " ", html)

但由于我不经常处理正则表达式,我不知道如何解决我所追求的。

标签: pythonregex

解决方案


尝试使用匹配所有空白字符的 \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.'

推荐阅读