Python正则表达式 - r前缀

Python正则表达式 - r前缀

任何人都可以解释为什么下面的示例1有效,何时r不使用前缀?我认为r只要使用转义序列,就必须使用前缀。示例2和示例3证明了这一点。


# example 1

import re

print (re.sub('\s+', ' ', 'hello     there      there'))

# prints 'hello there there' - not expected as r prefix is not used


# example 2

import re

print (re.sub(r'(\b\w+)(\s+\1\b)+', r'\1', 'hello     there      there'))

# prints 'hello     there' - as expected as r prefix is used


# example 3

import re

print (re.sub('(\b\w+)(\s+\1\b)+', '\1', 'hello     there      there'))

# prints 'hello     there      there' - as expected as r prefix is not used


HUX布斯
浏览 865回答 3
3回答

波斯汪

并非所有涉及反斜杠的序列都是转义序列。\t并且\f是,例如,但\s并非如此。在非原始字符串文字中,任何\不属于转义序列的内容都被视为另一个\:>>> "\s"'\\s'>>> "\t"'\t'\b 然而,是一个转义序列,因此示例3失败了。(是的,有些人认为这种行为很不幸。)
打开App,查看更多内容
随时随地看视频慕课网APP