我有一个功能:
find = re.compile(ur"\s+(Word)\s+", flags = re.U)
text = find.sub('\1', text)
我想找到一些像这样的模式“ Word
”(带有前缀/后缀空格)并将其替换为“Word”(没有这些空格)。在红宝石中,我以前做过这样的事情:
text.gsub('\s+(Word)\s+', '\1')
编辑:我的意思是我需要用一个新的字符串或其他东西来改变这些空间,这取决于情况。
问题是 Python 将您的 '\1' 解释为特殊的反斜杠字符;您需要使用原始字符串,这可以通过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'
尝试这个:
regcom = re.compile('\s+Word\s+', re.UNICODE)
print regcom.sub(u'Word', u'This is a Word ')
u'This is aWord'