首页 » SEO优化 » php正则多行技巧_正则表达式中的多行匹配模式

php正则多行技巧_正则表达式中的多行匹配模式

访客 2024-11-02 0

扫一扫用手机浏览

文章目录 [+]

利用正则表达式去匹配一大块的文本,你须要超过多行去匹配。

这个问题很范例的涌如今当你用点 (.) 去匹配任意字符的时候,忘却了点 (.) 不能匹配换行符的事实。
比如:

php正则多行技巧_正则表达式中的多行匹配模式

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))# []

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

php正则多行技巧_正则表达式中的多行匹配模式
(图片来自网络侵删)

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标志,则它匹配包括换行符在内的任何字符。

相关文章

我国土地利用分类代码的构建与应用

土地利用分类代码是我国土地管理的重要组成部分,是土地资源调查、规划、利用和保护的依据。土地利用分类代码的构建与应用显得尤为重要。本...

SEO优化 2025-02-18 阅读1 评论0

微信跳转微信支付便捷支付体验的秘密武器

移动支付已成为人们日常生活中不可或缺的一部分。作为我国领先的社交平台,微信支付凭借其便捷、安全的支付方式,深受广大用户的喜爱。而微...

SEO优化 2025-02-18 阅读1 评论0

探寻会计科目代码背后的奥秘分类与

会计科目代码是会计信息系统中不可或缺的组成部分,它将企业的经济活动进行分类和归纳,为会计核算、财务分析和决策提供重要依据。本文将从...

SEO优化 2025-02-18 阅读1 评论0