我有一个函数:
find = re.compile(ur"\s+(Word)\s+", flags = re.U)
text = find.sub('\1', text)
我想找到像这样的模式“Word
”(带有前缀/后缀空格)并将其替换为“Word”(没有这些空格)。在 ruby 中,我以前用这样的东西做过:
text.gsub('\s+(Word)\s+', '\1')
编辑:我的意思是我需要根据情况使用新字符串或其他内容更改这些空格。
最佳答案
问题是 Python 将你的 '\1' 解释为一个特殊的反斜杠字符;你需要使用 raw string ,这可以通过在字符串前添加一个 r
来完成。变化
find.sub('\1', text)
到
find.sub(r'\1', text)
例子:
text = "Replace this Word "
find = re.compile(ur"\s+(Word)\s+", flags = re.U)
find.sub(r'\1', text)
# 'Replace thisWord'
关于从模式的某个位置替换 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846076/