什么';Python中原始字符串上的隐式行联接需要

什么';Python中原始字符串上的隐式行联接需要,python,regex,string,multiline,rawstring,Python,Regex,String,Multiline,Rawstring,为了清晰起见,我想将正则表达式拆分为多行,但我不确定使用原始字符串是最好的方法 SECT_EXP = ( r'^(?P<number>.+?[.]? {1,2}' # Begin number pattern match r'(?P<sect_num>' # Begin section number match r'(?P<full_num>' # Begin full number match r'(?P<titl

为了清晰起见,我想将正则表达式拆分为多行,但我不确定使用原始字符串是最好的方法

SECT_EXP = (
    r'^(?P<number>.+?[.]? {1,2}'  # Begin number pattern match
    r'(?P<sect_num>'  # Begin section number match
    r'(?P<full_num>'  # Begin full number match
    r'(?P<title>\d{1,2}?)'  # Match title substring
    r'(?P<chapter>\d{2})'  # Match chapter substring
    r')'  # End full number match
    r'[.]'
    r'(?P<section>\d+)'  # Match section substring
    r')'  # End section number match
    r')'  # End number pattern match
    r'([.]?)[ ]*$'  # Lazy matching end of strings
)
SECT_EXP=(
r'^(?P.+?[.]?{1,2}'#开始数字模式匹配
r'(?P'#开始节号匹配
r'(?P'#开始全数字匹配
r'(?P\d{1,2}?)#匹配标题子字符串
r'(?P\d{2})#匹配章节子字符串
r')'#结束完整数字匹配
r'[.]'
r'(?P\d+)#匹配节子字符串
r')'#端段编号匹配
r')'#结束编号模式匹配
r'([.]?)[]*$'#字符串的惰性匹配结尾
)
但我是否需要在每个字符串前面加上r,以确保在使用隐式换行时整个字符串都作为原始字符串处理?

来自第页:

此标志允许您编写外观更好的正则表达式。模式中的空白将被忽略,除非在字符类中或前面有一个未缩放的反斜杠,并且当一行既不在字符类中也不在前面有一个未缩放的反斜杠时,从最左边的“#”到行尾的所有字符都将被忽略

这意味着以下两个匹配十进制数的正则表达式对象在功能上相等:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)

b = re.compile(r"\d+\.\d*")
如您所见,可以使用带有“r”前缀的三引号字符串,如上所示。

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)

b = re.compile(r"\d+\.\d*")