<jupyter_start><jupyter_text>正则表达式  常见匹配模式 | 模式| 描述||----|----|| \w	| 匹配字母数字及下划线 || \W	| 匹配非字母数字下划线 || \s	| 匹配任意空白字符，等价于 [\t\n\r\f]. || \S	| 匹配任意非空字符 || \d	| 匹配任意数字，等价于 [0-9] || \D	| 匹配任意非数字 || \A	| 匹配字符串开始 || \Z	| 匹配字符串结束，如果是存在换行，只匹配到换行前的结束字符串 || \z	| 匹配字符串结束 || \G	| 匹配最后匹配完成的位置 || \n | 匹配一个换行符 || \t | 匹配一个制表符 || ^	| 匹配字符串的开头 || $	| 匹配字符串的末尾。|| .	| 匹配任意字符，除了换行符，当re.DOTALL标记被指定时，则可以匹配包括换行符的任意字符。|| [...]	| 用来表示一组字符,单独列出：[amk] 匹配 'a'，'m'或'k' || [^...]	| 不在[]中的字符：[^abc] 匹配除了a,b,c之外的字符。| | *	| 匹配0个或多个的表达式。|| +	| 匹配1个或多个的表达式。|| ?	| 匹配0个或1个由前面的正则表达式定义的片段，非贪婪方式| | {n}	| 精确匹配n个前面表达式。|| {n, m} | 匹配 n 到 m 次由前面的正则表达式定义的片段，贪婪方式| | a&124;b | 匹配a或b || ( )	| 匹配括号内的表达式，也表示一个组 |  re.matchre.match 尝试从字符串的起始位置匹配一个模式，如果不是起始位置匹配成功的话，match()就返回none。<jupyter_code>re.match(pattern, string, flags=0)<jupyter_output><empty_output><jupyter_text>最常规的匹配<jupyter_code>import re

content = 'Hello 123 4567 World_This is a Regex Demo'
# 一共41个字符.空格也算.
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())<jupyter_output>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)<jupyter_text>泛匹配<jupyter_code>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())<jupyter_output><_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)<jupyter_text>匹配目标<jupyter_code>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(1))
print(result.span())<jupyter_output><_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
1234567
(0, 40)<jupyter_text>贪婪匹配<jupyter_code>import re

content = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^He.*(\d+).*Demo$', content)
print(result)
print(result.group(1))<jupyter_output><_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
7<jupyter_text>非贪婪匹配<jupyter_code>import re

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

content = '''Hello 1234567 World_This
is a Regex Demo
'''
result = re.match('^He.*?(\d+).*?Demo$', content, re.S)
print(result.group(1))

type(content)<jupyter_output>1234567<jupyter_text>转义<jupyter_code>import re

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

content = 'price is $5.00'
result = re.match('price is \$5\.00', content)
print(result)<jupyter_output><_sre.SRE_Match object; span=(0, 14), match='price is $5.00'><jupyter_text>总结：尽量使用泛匹配、使用括号得到匹配目标、尽量使用非贪婪模式、有换行符就用re.S  re.searchre.search 扫描整个字符串并返回第一个成功的匹配。<jupyter_code>import re

content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
result = re.match('Hello.*?(\d+).*?Demo', content)
print(result)
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))<jupyter_output><_sre.SRE_Match object; span=(13, 53), match='Hello 1234567 World_This is a Regex Demo'>
1234567<jupyter_text>总结：为匹配方便，能用search就不用match  匹配演练<jupyter_code>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))
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>'''
result = re.search('<li.*?singer="(.*?)">(.*?)</a>', html, re.S)
if result:
    print(result.group(1), result.group(2))
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>'''
result = re.search('<li.*?singer="(.*?)">(.*?)</a>', html)
if result:
    print(result.group(1), result.group(2))<jupyter_output>beyond 光辉岁月<jupyter_text>re.findall搜索字符串，以列表形式返回全部能匹配的子串。<jupyter_code>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])
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.*?>\s*?(<a.*?>)?(\w+)(</a>)?\s*?</li>',                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              html, re.S)
# print(results)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
for result in results:
    print(result[1])<jupyter_output>一路上有你
沧海一声笑
往事随风
光辉岁月
记事本
但愿人长久<jupyter_text>re.sub替换字符串中每一个匹配的子串后返回替换后的字符串。<jupyter_code>import re

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

content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
content = re.sub('\d+', 'Replacement', content)
print(content)
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)
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>'''

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())<jupyter_output><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">
            沧海一声笑
        </li>
        <li data-view="4" class="active">
            往事随风
        </li>
        <li data-view="6">光辉岁月</li>
        <li data-view="5">记事本</li>
        <li data-view="5">
            但愿人长久
        </li>
    </ul>
</div>
['一路上有你', '\n            沧海一声笑\n        ', '\n            往事随风\n        ', '光辉岁月', '记事本', '\n            但愿人长久\n        ']
一路上有你
沧海一声笑
往事随风
光辉岁月
记事本
但愿人长久<jupyter_text>re.compile将正则字符串编译成正则表达式对象<jupyter_code>将一个正则表达式串编译成正则对象，以便于复用该匹配模式
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)<jupyter_output><_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This\nis a Regex Demo'><jupyter_text>实战练习<jupyter_code>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)
import re 
content='''
<li class="mp-like-item mp-border-bottom">
    <a class="mp-fulllink" href="http://touch.piao.qunar.com/touch/detail.htm?id=777857128&amp;
        from=as_recommend_sight" data-click="ts_guess_like" data-click-index="0">
        
        <div class="mp-like-imgcon image-ready">            
            <img class="mp-like-img" src="http://img1.qunarzz.com/sight/p0/1708/2b/2b3b94de99c0a425a3.img.jpg_200x200_2458ffb2.jpg" alt="八达岭长城">
        </div>
        
        <div class="mp-like-tag" 
            style="background-image:url(https://img1.qunarzz.com/piao/fusion/1802/52/b9080e45b69b4f02.png)">
            可订明日
        </div>
        
        <div class="mp-like-info">
        
            <div class="mp-like-title mp-ellipsis">八达岭长城</div>
            
            <div class="mp-like-comment">
                <span class="mpf-starlevel" mp-role="star" data-score="4.9">
                    <strong class="mpg-iconfont mpf-starlevel-gain" mp-role="starWidth" style="width: 98%;">
                        
                    </strong>
                    <span class="mpg-iconfont mpf-starlevel-total"></span>
                </span>
                <span class="mp-comment-num">
                    42790条评论
                </span>
            </div>
            <div class="mp-like-price">
                <span class="mpg-price">¥
                    <em class="mpg-price-num">157.5</em>
                </span>起
                <span class="mp-like-address">
                    延庆县
                </span>
            </div>
            <div class="mp-like-feature">
                <div class="mp-ellipsis2">
                    不到长城非好汉
                </div>
            </div>
        </div>
    </a>
</li>
'''
pattern = re.compile('<li.*?mp-like-img.*?src="(.*?)".*?mp-ellipsis">(.*?)</div>.*?data-score="(.*?)".*?mp-comment-num">\s*?(.*?)条评论\s*?</span>.*?mpg-price-num">(.*?)</em>.*?mp-like-address">(.*?)</span>.*?mp-ellipsis2">(.*?)</div>.*?</li>',re.S)
results = re.findall(pattern,content)
print(results)
import re 
import requests
content = requests.get('http://touch.piao.qunar.com/').text
pattern = re.compile('<li.*?mp-like-img.*?src="(.*?)".*?mp-ellipsis">(.*?)</div>.*?data-score="(.*?)".*?mp-comment-num">\s*?(.*?)条评论\s*?</span>.*?mpg-price-num">(.*?)</em>.*?mp-like-address">(.*?)</span>.*?</li>',re.S)
results = re.findall(pattern,content)
print(results)
import re 
content ='''
<div class="mp-like-tag" 
    style="background-image:url(https://img1.qunarzz.com/piao/fusion/1802/52/b9080e45b69b4f02.png)">
    可订明日
</div>
'''
pattern = re.compile('(<div.*?style="(.*?)">)?(.*?)(/div)',re.S)
results = re.findall(pattern,content)
print(results)
import re
content = '''<li data-view="5"><a href="/5.mp3" singer="陈慧琳">记事本</a></li>'''
pattern = re.compile('<li.*?>\s*?(<a.*?>)?(\w+)(</a>)?.*?</li>',re.S)
results = re.findall(pattern,content)
print(results)                     
import re
content = '''
<li class="mp-like-item mp-border-bottom">
    <a class="mp-fulllink" href="http://touch.piao.qunar.com/touch/detail.htm?id=4294756599&amp;from=as_recommend_sight" 
        data-click="ts_guess_like" data-click-index="1">
            <div class="mp-like-imgcon image-ready">
                <img class="mp-like-img" src="http://img1.qunarzz.com/sight/p0/1611/96/96c7b547622c8334a3.img.jpg_200x200_cd0b30b0.jpg" alt="西山温泉">
            </div>
            <div class="mp-like-info">
                <div class="mp-like-title mp-ellipsis">西山温泉</div>
                <div class="mp-like-comment">
                    <span class="mpf-starlevel" mp-role="star" data-score="4.9">
                        <strong class="mpg-iconfont mpf-starlevel-gain" mp-role="starWidth" style="width: 98%;">
                        
                        </strong>
                        <span class="mpg-iconfont mpf-starlevel-total">
                        
                        </span>
                    </span>
                    <span class="mp-comment-num">275条评论</span>
                </div>
                <div class="mp-like-price">
        
                <span class="mpg-price">
                    ¥<em class="mpg-price-num">218</em>
                </span>起
            
                <span class="mp-like-address">海淀区</span>
            </div>
        </div>
    </a>
</li>
'''
pattern = re.compile('<li.*?mp-like-img.*?src="(.*?)".*?mp-ellipsis">(.*?)</div>.*?data-score="(.*?)".*?mp-comment-num">\s*?(.*?)条评论\s*?</span>.*?mpg-price-num">(.*?)</em>.*?mp-like-address">(.*?)</span>.*?mp-ellipsis2">(.*?)</div>.*?</li>',re.S)
results = re.findall(pattern,content)
print(results)<jupyter_output>[]
{'fraction_non_alphanumeric': 0.14274656780869352, 'fraction_numerical': 0.02212082942925816, 'mean_word_length': 0.9124337799937675, 'pattern_counts': {'":': 0, '<': 399, '<?xml version=': 0, '>': 411, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 466, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '392214', 'license': 'MIT', 'n_tokens_mistral': 7309, 'n_tokens_neox': 7349, 'n_words': 1031, 'path': 'jupyterworkflow/tests/regex.ipynb', 'repo_name': 'lovemoganna/jupyterworkspace', 'size': '24547'}