1. 程式人生 > >python正則表達式3-模式匹配

python正則表達式3-模式匹配

dex import mail blog 正則表達 gpo .cn span OS

re.S,使 ‘.‘ 匹配換行在內的所有字符

>>> pattern=rghostwu.com
>>> import re
>>> re.findall( pattern, ghostwuacom )
[ghostwuacom]
>>> re.findall( pattern, ghostwubcom ) 
[ghostwubcom]
>>> re.findall( pattern, ghostwu.com ) 
[ghostwu.com]
>>> re.findall( pattern, 
ghostwu\ncom ) [] >>> re.findall( pattern, ghostwu\ncom, re.S ) [ghostwu\ncom] >>>

re.M,多行匹配,主要影響( ^和$ )

>>> str="""
... hi,ghostwu,how are you
... ghostwu: my name is ghostwu,how are you
... ghostwu: nice to meet you
... hello ghostwu
... """
>>> pattern = r"
^ghostwu" >>> re.findall( pattern, str ) [] >>> re.findall( pattern, str, re.M ) [ghostwu, ghostwu] >>>

當正則有多行的時候,可以開啟verbose模式re.X

>>> pattern=r"""
... \d{3,4}
... -?
... \d{8}
... """
>>> str="020-88888888"
>>> re.findall( pattern, str )
[]
>>> re.findall( pattern, str, re.X ) [020-88888888] >>>

():分組與| 的使用, 假如我們要匹配一個.com,.cn,.net結尾的email

>>> pattern=r"\w+@\w+(.com|.cn|.net)"
>>> email="[email protected]">>> re.match( pattern, email )
<_sre.SRE_Match object at 0x7f2b74481828>
>>> re.match( pattern, [email protected] )
<_sre.SRE_Match object at 0x7f2b744818a0>
>>> re.match( pattern, [email protected] )
<_sre.SRE_Match object at 0x7f2b74481828>
>>> re.match( pattern, [email protected] )
>>> 

匹配超鏈接

>>> html="""
... <a href="http://www.baidu.com">百度</a>
... <a href="index.html">首頁</a>
... <p>這是一段說明</p>
... <a href="http://www.taobao.com">淘寶</a>
... """
>>> re=r"href=\"(.+?)\""
>>> pattern=r"href=\"(.+?)\""
>>> re
href=\\"(.+?)\\"
>>> import re
>>> re.findall( pattern, html )
[http://www.baidu.com, index.html, http://www.taobao.com]
>>> 

python正則表達式3-模式匹配