Python 正则表达式,多行匹配模式.. 为什么这不起作用?

标签 python regex parsing

我知道对于解析我应该理想地删除所有空格和换行符但我这样做只是为了快速修复我正在尝试的东西而且我无法弄清楚为什么它不起作用..我已经包装了不同的区域我的文档中的文本带有“####1”之类的包装器,我正在尝试基于此进行解析,但无论我尝试什么,它都无法正常工作,我认为我正在正确使用多行.. 任何建议都表示赞赏

这根本不返回任何结果:

string='
####1
ttteest
####1
ttttteeeestt

####2   

ttest
####2'

import re
pattern = '.*?####(.*?)####'
returnmatch = re.compile(pattern, re.MULTILINE).findall(string)
return returnmatch

最佳答案

Multiline 并不意味着 . 将匹配行返回,这意味着 ^$ 仅限于行

re.M re.MULTILINE

When specified, the pattern character '^' matches at the beginning of the string and at the >beginning of each line (immediately following each newline); and the pattern character '$' >matches at the end of the string and at the end of each line (immediately preceding each >newline). By default, '^' matches only at the beginning of the string, and '$' only at the >end of the string and immediately before the newline (if any) at the end of the string.

re.Sre.DOTALL 使 . 甚至匹配新行。

来源

http://docs.python.org/

关于Python 正则表达式,多行匹配模式.. 为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3534507/

相关文章:

java - 如何组成正则表达式过滤掉以==开头和==结尾的单词?

python - 在 matplotlib 中,有没有办法在条/线/补丁下方设置网格线,同时保留上方的刻度标签?

regex - 如何根据给定的正则表达式构造一个CFG

Python:使用 pre 和 post 方法包装方法调用

regex - 持续模式匹配来识别 SQL 子句

regex - DOM 解析、结构化文档底层遍历

ruby - 使用 Nokogiri 从提要中提取 URL

java - 如何修复意外的文档结束异常

python - 在线工具和Python脚本有两个不同的AES密文结果?

python - Matplotlib PCA 示例在更改尺寸后不起作用