1. 程式人生 > >python-re正則表示式

python-re正則表示式

正則表示式

# 一個線上正則表示式工具
http://tool.oschina.net/regex/
模式 描述
\w 匹配字母數字及下劃線
\W 匹配非字母數字下劃線
\s 匹配任意空白字元,等價於 [\t\n\r\f].
\S 匹配任意非空字元
\d 匹配任意數字,等價於 [0-9]
\D 匹配任意非數字
\A \A 匹配字串開始
\Z \Z 匹配字串結束,如果是存在換行,只匹配到換行前的結束字串
\z \z 匹配字串結束
\G \G 匹配最後匹配完成的位置
\n \n 匹配一個換行符
\t \t 匹配一個製表符
^ ^ 匹配字串的開頭
$ $ 匹配字串的末尾。
. .匹配任意字元,除了換行符,當re.DOTALL標記被指定時,則可以匹配包括換行符的任意字元。
[…] […] 用來表示一組字元,單獨列出:[amk] 匹配 ‘a’,‘m’或’k’
[^…] [^…] 不在[]中的字元:[^abc] 匹配除了a,b,c之外的字元。
* * 匹配0個或多個的表示式。
+ + 匹配1個或多個的表示式。
? ? 匹配0個或1個由前面的正則表示式定義的片段,非貪婪方式
{n} {n} 精確匹配n個前面表示式。
{n, m} {n, m} 匹配 n 到 m 次由前面的正則表示式定義的片段,貪婪方式
a|b a|b 匹配a或b
( ) ( ) 匹配括號內的表示式,也表示一個組

re.match

"""
match 第一個字元開始匹配

re.match 嘗試從字串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。
re.match(pattern, string, flags=0)
pattern, string, flags=0 
正則表示式,要匹配的字串 匹配模式

儘量使用泛匹配、使用括號得到匹配目標、儘量使用非貪婪模式、有換行符就用re.S
"""

# 常規練習匹配
import re

content = 'Hello 123 4567 World_This is a Regex Demo'
print(len(content))
result = re.match('^Hello\s\d\d\d\s\d{4}\s\w{10}.*Demo$', content)
print(result)
print(result.group()) #返回匹配結果
print(result.span())  # 輸出匹配結果的範圍
"""
41
<_sre.SRE_Match object; span=(0, 41), match='Hello 123 4567 World_This is a Regex Demo'>
Hello 123 4567 World_This is a Regex Demo
(0, 41)
"""


# 泛匹配
import re

content = 'Hello 123 4567 World_This is a Regex Demo'
result = re.match('^Hello.*Demo$', content)
print(result)
print(result.group())
print(result.span())
"""
<_sre.SRE_Match object; span=(0, 41), match='Hello 123 4567 World_This is a Regex Demo'>
Hello 123 4567 World_This is a Regex Demo
(0, 41)
"""


# 目標匹配,使用小括號 括起來
import re

content = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^Hello\s(\d+)\sWorld.*Demo$', content)
print(result)
print(result.group())
print(result.group(1))
print(result.span())
"""
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
Hello 123 4567 World_This is a Regex Demo
1234567
(0, 40)
"""


# 貪婪匹配
import re

content = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^He.*(\d+).*Demo$', content)
print(result)
print(result.group(1))
"""
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
7
# 只匹配出了7,是因為前面 .*是貪婪的,把123456匹配走了,匹配儘可能的多
"""

# 非貪婪匹配  ?匹配儘可能少的字元
import re

content = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^He.*?(\d+).*Demo$', content)
print(result)
print(result.group(1))
"""
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
1234567
"""



# 匹配模式 re.S
import re

content = '''Hello 1234567 World_This
is a Regex Demo
'''
result = re.match('^He.*?(\d+).*?Demo$', content, re.S)
print(result.group(1))
"""
1234567
# 如果不加re.S,匹配是空,因為.*不能匹配換行符
"""



# 轉移
import re

content = 'price is $5.00'
result = re.match('price is $5.00', content)
print(result)
"""
None
"""

import re
content = 'price is $5.00'
result = re.match('price is \$5\.00', content)
print(result)
"""
<_sre.SRE_Match object; span=(0, 14), match='price is $5.00'>
"""



"""
總結:
	儘量使用泛匹配、使用括號得到匹配目標、儘量使用非貪婪模式、有換行符就用re.S
"""

re.search

# match 和 search

import re
content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
result = re.match('Hello.*?(\d+).*?Demo', content)
print(result)
# None

import re
content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
result = re.search('Hello.*?(\d+).*?Demo', content)
print(result)
print(result.group(1))
# <_sre.SRE_Match object; span=(13, 53), match='Hello 1234567 World_This is a Regex Demo'>
# 1234567
# 匹配練習
import re

html = '''<div id="songs-list">
    <h2 class="title">經典老歌</h2>
    <p class="introduction">
        經典老歌列表
    </p>
    <ul id="list" class="list-group">
        <li data-view="2">一路上有你</li>
        <li data-view="7">
            <a href="/2.mp3" singer="任賢齊">滄海一聲笑</a>
        </li>
        <li data-view="4" class="active">
            <a href="/3.mp3" singer="齊秦">往事隨風</a>
        </li>
        <li data-view="6"><a href="/4.mp3" singer="beyond">光輝歲月</a></li>
        <li data-view="5"><a href="/5.mp3" singer="陳慧琳">記事本</a></li>
        <li data-view="5">
            <a href="/6.mp3" singer="鄧麗君"><i class="fa fa-user"></i>但願人長久</a>
        </li>
    </ul>
</div>'''
result = re.search('<li.*?active.*?singer="(.*?)">(.*?)</a>', html, re.S)
if result:
    print(result.group(1), result.group(2))
   	# 齊秦 往事隨風

result = re.search('<li.*?singer="(.*?)">(.*?)</a>', html, re.S)
if result:
    print(result.group(1), result.group(2))
    # 任賢齊 滄海一聲笑
    
    
result = re.search('<li.*?singer="(.*?)">(.*?)</a>', html)
if result:
    print(result.group(1), result.group(2))
    # beyond 光輝歲月

re.findall

# 搜尋字串,以列表形式返回全部能匹配的子串。

import re

html = '''<div id="songs-list">
    <h2 class="title">經典老歌</h2>
    <p class="introduction">
        經典老歌列表
    </p>
    <ul id="list" class="list-group">
        <li data-view="2">一路上有你</li>
        <li data-view="7">
            <a href="/2.mp3" singer="任賢齊">滄海一聲笑</a>
        </li>
        <li data-view="4" class="active">
            <a href="/3.mp3" singer="齊秦">往事隨風</a>
        </li>
        <li data-view="6"><a href="/4.mp3" singer="beyond">光輝歲月</a></li>
        <li data-view="5"><a href="/5.mp3" singer="陳慧琳">記事本</a></li>
        <li data-view="5">
            <a href="/6.mp3" singer="鄧麗君">但願人長久</a>
        </li>
    </ul>
</div>'''
results = re.findall('<li.*?href="(.*?)".*?singer="(.*?)">(.*?)</a>', html, re.S)
print(results)
print(type(results))
for result in results:
    print(result)
    print(result[0], result[1], result[2])
    
"""
[('/2.mp3', '任賢齊', '滄海一聲笑'), ('/3.mp3', '齊秦', '往事隨風'), ('/4.mp3', 'beyond', '光輝歲月'), ('/5.mp3', '陳慧琳', '記事本'), ('/6.mp3', '鄧麗君', '但願人長久')]
<class 'list'>

('/2.mp3', '任賢齊', '滄海一聲笑')
/2.mp3 任賢齊 滄海一聲笑
('/3.mp3', '齊秦', '往事隨風')
/3.mp3 齊秦 往事隨風
('/4.mp3', 'beyond', '光輝歲月')
/4.mp3 beyond 光輝歲月
('/5.mp3', '陳慧琳', '記事本')
/5.mp3 陳慧琳 記事本
('/6.mp3', '鄧麗君', '但願人長久')
/6.mp3 鄧麗君 但願人長久

"""




results = re.findall('<li.*?>\s*?(<a.*?>)?(\w+)(</a>)?\s*?</li>', html, re.S)
print(results)
for result in results:
    print(result[1])
"""
[('', '一路上有你', ''), ('<a href="/2.mp3" singer="任賢齊">', '滄海一聲笑', '</a>'), ('<a href="/3.mp3" singer="齊秦">', '往事隨風', '</a>'), ('<a href="/4.mp3" singer="beyond">', '光輝歲月', '</a>'), ('<a href="/5.mp3" singer="陳慧琳">', '記事本', '</a>'), ('<a href="/6.mp3" singer="鄧麗君">', '但願人長久', '</a>')]
一路上有你
滄海一聲笑
往事隨風
光輝歲月
記事本
但願人長久
"""

re.sub

# 替換字串中每一個匹配的子串後返回替換後的字串。

import re
content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
content = re.sub('\d+', '', content)
print(content)
# Extra stings Hello  World_This is a Regex Demo Extra stings

import re
content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
content = re.sub('\d+', 'Replacement', content)
print(content)
# Extra stings Hello Replacement World_This is a Regex Demo Extra stings

import re
content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
content = re.sub('(\d+)', r'\1 8910', content)
print(content)
# Extra stings Hello 1234567 8910 World_This is a Regex Demo Extra stings



import re
html = '''<div id="songs-list">
    <h2 class="title">經典老歌</h2>
    <p class="introduction">
        經典老歌列表
    </p>
    <ul id="list" class="list-group">
        <li data-view="2">一路上有你</li>
        <li data-view="7">
            <a href="/2.mp3" singer="任賢齊">滄海一聲笑</a>
        </li>
        <li data-view="4" class="active">
            <a href="/3.mp3" singer="齊秦">往事隨風</a>
        </li>
        <li data-view="6"><a href="/4.mp3" singer="beyond">光輝歲月</a></li>
        <li data-view="5"><a href="/5.mp3" singer="陳慧琳">記事本</a></li>
        <li data-view="5">
            <a href="/6.mp3" singer="鄧麗君">但願人長久</a>
        </li>
    </ul>
</div>'''
html = re.sub('<a.*?>|</a>', '', html)
print(html)
results = re.findall('<li.*?>(.*?)</li>', html, re.S)
print(results)
for result in results:
    print(result.strip()) # 去掉換行符等

re.compile

# 將一個正則表示式串編譯成正則物件,以便於複用該匹配模式
import re

content = '''Hello 1234567 World_This
is a Regex Demo'''
pattern = re.compile('Hello.*Demo', re.S)
result = re.match(pattern, content)
#result = re.match('Hello.*Demo', content, re.S)
print(result)
# <_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This\nis a Regex Demo'>

實戰練習

import requests
import re
content = requests.get('https://book.douban.com/').text
pattern = re.compile('<li.*?cover.*?href="(.*?)".*?title="(.*?)".*?more-meta.*?author">(.*?)</span>.*?year">(.*?)</span>.*?</li>', re.S)
results = re.findall(pattern, content)
for result in results:
    url, name, author, date = result
    author = re.sub('\s', '', author)
    date = re.sub('\s', '', date)
    print(url, name, author, date)