python正则表达式不包含python多⾏字符串变单⾏_Python正则表达式⾥的单⾏re.S和
多⾏re.M模式
Python正则表达式⾥的单⾏re.S和多⾏re.M模式
Python 的re模块内置函数⼏乎都有⼀个flags参数,以位运算的⽅式将多个标志位相加。其中有两个模式:单⾏(re.DOTALL, 或者re.S)和多⾏(re.MULTILINE, 或者re.M)模式。它们初看上去不好理解,但是有时⼜会⾮常有⽤。这两个模式在PHP和JavaScripts⾥都有。
单⾏模式 re.DOTALL
在单⾏模式⾥,⽂本被强制当作单⾏来匹配,什么样的⽂本不会被当作单⾏?就是⾥⾯包含有换⾏符的⽂本,⽐如:
This is the first line.\nThis is the second line.\nThis is the third line.
点号(.)能匹配所有字符,换⾏符例外。现在我们希望能匹配出整个字符串,当⽤点号(.)匹配上⾯这个字符串时,在换⾏符的地⽅,匹配停⽌。例如:
>>> a = 'This is the first line.\nThis is the second line.\nThis is the third line.'
>>> print a
This is the first line.
This is the second line.
This is the third line.
>>> import re
>>> p = re.match(r'This.*line.' ,a)
>>> p.group(0)
'This is the first line.'
>>>
在上⾯的例⼦⾥,即使是默认贪婪(greedy)的匹配,仍然在第⼀⾏的结尾初停⽌了匹配,⽽在单⾏模式下,换⾏符被当作普通字符,被点号(.)匹配:
>>> q = re.match(r'This.*line.', a, flags=re.DOTALL)
>>> q.group(0)
'This is the first line.\nThis is the second line.\nThis is the third line.'
点号(.)匹配了包括换⾏符在内的所有字符。所以,更本质的说法是
单⾏模式改变了点号(.)的匹配⾏为
多⾏模式 re.MULTILINE
在多⾏模式⾥,⽂本被强制当作多⾏来匹配。正如上⾯单⾏模式⾥说的,默认情况下,⼀个包含换⾏符的字符串总是被当作多⾏处理。但是⾏⾸符^和⾏尾符$仅仅匹配整个字符串的起始和结尾。这个时候,包含换⾏符的字符串⼜好像被当作⼀个单⾏处理。
在下⾯的例⼦⾥,我们希望能将三句话分别匹配出来。⽤re.findall( )显⽰所有的匹配项
>>> a = 'This is the first line.\nThis is the second line.\nThis is the third line.'
>>> print a
This is the first line.
This is the second line.
This is the third line.
>>> import re
>>> re.findall(r'^This.*line.$', a)
[]
>>>
默认点号不匹配换⾏符,我们需要设置re.DOTALL。
>>> re.findall(r'^This.*line.$', a, flags=re.DOTALL)
['This is the first line.\nThis is the second line.\nThis is the third line.']
>>>
匹配出了整句话,因为默认是贪婪模式,⽤问号切换成⾮贪婪模式:
>>> re.findall(r'^This.*?line.$', a, flags=re.DOTALL)
['This is the first line.\nThis is the second line.\nThis is the third line.']
>>>
仍然是整句话,这是因为^和$只匹配整个字符串的起始和结束。在多⾏模式下,^除了匹配整个字符串的起始位置,还匹配换⾏符后⾯的位置;$除了匹配整个字符串的结束位置,还匹配换⾏符前⾯的位置.
>>> re.findall(r'^This.*?line.$', a, flags=re.DOTALL+re.MULTILINE)
['This is the first line.', 'This is the second line.', 'This is the third line.']
>>>
更本质的说法是
多⾏模式改变了^和$的匹配⾏为
本⽂转⾃:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。