带有空格的Regex子字符串

问题描述 投票:0回答:1

我想替换或替换字符串中的子字符串。在子字符串仅包含空格之前,此方法可以正常工作。

substring= "\n\t\t\t"
string = "<!-- xx -->\n\t\t\t<!-- yy -->"
wanted_result = "<!-- xx --><!-- yy -->"

当前,如果使用这两行之一

result = re.sub(substring, '', string)
result = string.replace(substring, '')

它只返回字符串作为结果,而不更改字符串上的任何内容。

我真的很感谢您的帮助! :)

python regex python-3.x removing-whitespace
1个回答
0
投票

尝试此

Regex:

[\t\n\s]

代码

import re

pattern = r'[\t\n\s]'
string = '<!-- xx -->\n\t\t\t<!-- yy -->'
result = re.sub(pattern, '', string)

Demo: Here

© www.soinside.com 2019 - 2024. All rights reserved.