2019年9月24日 / 3,289次阅读 / Last Modified 2019年9月24日
re模块
Python支持正则表达式应用的模块re,有一个参数,叫作re.MULTILINE。由于re模块自然支持在多行字符串中进行匹配(可以直接匹配换行符\n),这个re.MULTILINE是什么意思呢?
如下是来Python官方的解释:
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. Corresponds to the inline flag(?m)
.
当使用re.MULTILINE时,^和$这两个符号的含义发生了一点变化,原来这两个符号表示整个字符串(可以有\n换行符的字符串)的开始和结束,加上re.MULTILINE参数后,含义变为每行的开始和结束。re.M是这个参数的简写。
示例代码:
>>> a = """\
... abcde12345
... 12345abcde
... xinlin
... 20110407
... """
>>> a
'abcde12345\n12345abcde\nxinlin\n20110407\n'
>>> import re
>>> re.findall('\d+', a)
['12345', '12345', '20110407']
>>> re.findall('^\d+', a, re.MULTILINE)
['12345', '20110407']
>>> re.findall('[a-z]+$', a)
[]
>>> re.findall('[a-z]+$', a, re.MULTILINE)
['abcde', 'xinlin']
设定了一个多行字符串a,然后使用re.findall('\d+',a),找出所有的数字串,这个操作已经跨行了。最后使用re.findall('^\d+', a, re.MULTILINE),找出每行开始的字符串。后面两次调用,匹配以小写字母结束的子串,而加上此参数后,就是在每一行中去寻找以小写字母结束的子串。
re.MULTILINE参数只是让^和$符号的含义发生了一点变化,在某些场合下,增加易用性。
-- EOF --
本文链接:https://www.pynote.net/archives/1197
前一篇:如何使用pack布局界面tkinter组件?
后一篇:re.DOTALL的使用
©Copyright 麦新杰 Since 2019 Python笔记