正则表达式匹配特定字(正则表达式中的多行匹配模式)

学习《Python Cookbook》第三版 使用正则表达式去匹配一大块的文本,你需要跨越多行去匹配 ,今天小编就来说说关于正则表达式匹配特定字?下面更多详细答案一起来看看吧!

正则表达式匹配特定字(正则表达式中的多行匹配模式)

正则表达式匹配特定字

学习《Python Cookbook》第三版

使用正则表达式去匹配一大块的文本,你需要跨越多行去匹配。

这个问题很典型的出现在当你用点 (.) 去匹配任意字符的时候,忘记了点 (.) 不能匹配换行符的事实。比如:

my_text = """ * The sky is blue, the sea is green. You are the everlasting sun in my heart. * """ my_text_one = '* The sky is blue, the sea is green. *' patter_compiled = re.compile(r'\*(.*)\*') print(patter_compiled.findall(my_text_one)) # [' The sky is blue, the sea is green. '] print(patter_compiled.findall(my_text)) # []

为了修正这个问题,你可以修改模式字符串,增加对换行的支持。比如:

my_text = """ * The sky is blue, the sea is green. You are the everlasting sun in my heart. * """ patter_compiled_mu = re.compile(r'\*((?:.|\n)*)\*') print(patter_compiled_mu.findall(my_text)) # [' The sky is blue, the sea is green.\n You are the everlasting sun in my heart. ']

在这个模式中, (?:.|\n) 指定了一个非捕获组 (也就是它定义了一个仅仅用来做匹配,而不能通过单独捕获或者编号的组)

re.compile() 函数接受一个标志参数叫 re.DOTALL ,在这里非常有用。它可以让正则表达式中的点 (.) 匹配包括换行符在内的任意字符。比如:

patter_compiled_dot = re.compile(r'\*(.*)\*', flags=re.DOTALL) print(patter_compiled_dot.findall(my_text)) # [' The sky is blue, the sea is green.\n You are the everlasting sun in my heart. ']

对于简单的情况使用 re.DOTALL 标记参数工作的很好,但是如果模式非常复杂或者是为了构造字符串令牌而将多个模式合并起来 ,这时候使用这个标记参数就可能出现一些问题。如果让你选择的话,最好还是定义自己的正则表达式模式,这样它可以在不需要额外的标记参数下也能工作的很好。

官方对于正则表达式中的点(.)的解释:

.(Dot.)

In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.

在默认模式下,它匹配除换行符以外的任何字符。 如果指定了DOTALL标志,则它匹配包括换行符在内的任何字符。

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页