多行匹配模式
一、 解决问题
需要跨越多行去匹配
当使用(.)去匹配任意字符的时候,点不能匹配换行符
二、解决方案
正则表达式 (?:.|\n)*
忽略标识 re.DOTALL
三、代码说明
import re
comment = re.compile(r'/\*(.*?)\*/')
text1 = '/* this is a comment */'
resval = comment.findall(text1)
print(resval)
text2 = """/* this is a
multiline 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