python - Python 中原始字符串的隐式行连接需要什么

标签 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<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
)

但是我是否需要在每个字符串前加上 r 以确保在使用隐式行连接时将整个字符串作为原始字符串处理?

最佳答案

来自 this页:

re.X
re.VERBOSE

此标志允许您编写看起来更好的正则表达式。模式中的空格将被忽略,除非在字符类中或前面有未转义的反斜杠,并且当一行包含 '#' 既不在字符类中也不包含未转义的反斜杠时,最左边的所有字符如 '# ' 到行尾都将被忽略。

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

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

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

如您所见,可以使用带有“r”前缀的三引号字符串,如上所示。

关于python - Python 中原始字符串的隐式行连接需要什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20955401/

相关文章:

c++ - 从正在运行的程序中读取值

python - 图像未加载到 py2exe 中 PyQt4 的 QWebview 中

python - 使用捕获组提取字符串(使用 re.match)

java - 遍历一个计数字符串值

java - java中检查两个字符串是否相等

python - 极值的 logit 和反 logit 函数

python - 如何对 Python 程序进行版本控制

regex - R:使用多个正则表达式模式和异常拆分文本

javascript - IE 8 中的正则表达式 (Javascript) 问题

c++ - 有一个 PCWSTR 并需要它成为一个 WCHAR[]