[00108]多行匹配模式

来源:互联网 发布:老同学好久不见网络语 编辑:程序博客网 时间:2024/05/27 14:15

多行匹配模式

一、 解决问题

需要跨越多行去匹配
当使用(.)去匹配任意字符的时候,点不能匹配换行符

二、解决方案

正则表达式 (?:.|\n)*
忽略标识 re.DOTALL

三、代码说明

import recomment = re.compile(r'/\*(.*?)\*/')text1 = '/* this is a comment */'resval = comment.findall(text1)print(resval)text2 = """/* this is amultiline comment */"""#匹配不到resval = comment.findall(text2)print(resval)
#1. 修改匹配方式"""(?:xxx) 指定了一个非捕获组。    也就是它定义了一个仅仅用来做匹配,而不能通过单独捕获或编号的组"""comment = re.compile(r"/\*((?:.|\n)*?)\*/")resval = comment.findall(text2)print(resval) #->[' this is a\nmultiline comment ']
# 2.添加re.DOTALL 忽略comment = re.compile(r'/\*(.*?)\*/', re.DOTALL)resval = comment.findall(text2)print(resval) #->[' this is a\nmultiline comment ']

四、关联知识

re模块 传送门,待补充

五、总结

六、代码地址

github地址:https://github.com/weichen666/python_cookbooka>
目录/文件:first_selection/learn_str_mutiline.py

七、参考

0 0
原创粉丝点击