最近做爬虫,把python基础的正则表达式又重新过了一遍。
常规匹配
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)
泛匹配
content = 'Hello 123 4567 World_this is a regex Demo'
result = re.match("^Hello.*Demo$", content)
匹配目标
获取1234567
result = re.match("^Hello\s(\d+)\s.*Demo$", content)
print(result.group(1))
输出:1234567
贪婪匹配
result = re.match("^He.*(\d+).*Demo$", content)
# 输出 7
非贪婪匹配
?:匹配尽可能少的字符
result = re.match("^He.*?(\d+).*Demo$", content)
# 输出1234567
匹配模式
- World_this之后进行了换行
- 参数后添加 re.S代表.*都能匹配
- .*匹配除了换行的任意字符
content = '''Hello 1234567 World_this is a regex Demo '''
result = re.match("^He.*?(\d+).*?Demo$", content, re.S)
转义
content = 'price is $10.00'
result = re.match('price is \$10\.00', content)
re.search
找一个结果
findall: 找所有
re.sub
字符串替换
content = "dimples 54 aaa"
result = re.sub('\d+', '', content)
print(result)
输出:
dimples aaa
替换原字符串本身或包含字符串
- \1 : 把第一个括号得内容拿过来做一些替换
content = "dimples 12345 aaa"
result = re.sub('(\d+)', r'\1 6789', content)
print(result)
输出:
dimples 12345 6789 aaa
结合使用
获取所有歌名
html = '''<li class="aaa">
<a href="2.mp3">借</a>
</li>
<li data-view="6">消愁</li>
'''
result1 = re.sub('<a.*?>|</a>', '', html)
print(result1)
result2 = re.findall('<li.*?>(.*?)</li>', result1, re.S)
for result in result2:
print(result.strip())
输出:
借
消愁
re.compile
把一个正则字符串编译成正则表达式对象,便于复用这个匹配模式
content = '''Hello 1234567 World_this is a regex Demo '''
pattern = re.compile("^He.*?(\d+).*?Demo$", re.S)
result = re.match(pattern, content)
print(result)
print(result.group(1))
# 输出: 1234567