正则语法

发布时间 2023-12-26 15:13:06作者: 蓝幻ﹺ

正则

字符组

  • [字符组] 在同一个位置可能出现的各种字符组成了一个字符组
  • 在正则表达式中用[]表示
[0123456789]       # 匹配0-9中某个字符的单个结果   
[0-9]			   # 匹配0-9中某个字符的单个结果   
[a-z]			   # 匹配a-z中某个字符的单个结果
[A-Z] 			   # 匹配A-Z中某个字符的单个结果
[0-9a-zA-Z]		   # 匹配数字或小写字母或大写字母的单个结果

元字符

元字符 匹配内容
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线
\s 匹配任意的空白符
\d 匹配数字
\n 匹配一个换行符
\t 匹配一个制表符
\b 匹配一个单词的结尾
^ 匹配字符串的开始
$ 匹配字符串的结尾
\W 匹配非字母或数字或下划线
\D 匹配非数字
\S 匹配非空白符
a|b 匹配字符a或字符b
() 匹配括号内的表达式,也表示一个组
[...] 匹配字符组中的字符
[^...] 匹配除了字符组中字符的所有字符

量词

量词 用法说明
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次

非贪婪模式

  • ?取消非贪婪模式
  • *? 重复任意次,但尽可能少重复
  • +? 重复1次或更多次,但尽可能少重复
  • ?? 重复0次或1次,但尽可能少重复
  • {n,m}? 重复n到m次,但尽可能少重复
  • {n,}? 重复n次以上,但尽可能少重复

re模块

import re
【1】查找结果(findall)
str = 'my name is qcc,my age is 18'

res = re.findall(pattern=r'\w', string=str)
print(res)
# ['m', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'q', 'c', 'c', 'm', 'y', 'a', 'g', 'e', 'i', 's', '1', '8']
【2】查找结果(search)
str = 'my name is qcc,my age is 18'

a = re.compile(pattern=r'\w')
res = re.search(pattern=a, string=str)
print(res)
# <re.Match object; span=(0, 1), match='m'>
print(res.group())
# m
【3】查找结果(match)
str = 'my name is qcc,my age is 18'

a = re.compile(pattern=r'\w')
res = re.match(pattern=a, string=str)
print(res)
# <re.Match object; span=(0, 1), match='m'>
print(res.group())
# m
【4】切割(split)
str = 'my name is qcc,my age is 18'

res = re.split(pattern='a', string=str)
print(res)
# ['my n', 'me is qcc,my ', 'ge is 18']
【5】指定个数替换(sub)
str = 'my name is qcc,my age is 18'

res = re.sub('\d', 'H', str, 1)
print(res)
# my name is qcc,my age is H8
【6】替换全部(subn)
str = 'my name is qcc,my age is 18'

res = re.subn('\d', 'H', str)
print(res)
# ('my name is qcc,my age is HH', 2)
【7】匹配结果为迭代器(finditer)
str = 'my age is 18'

res = re.finditer(pattern='\d*',string=str)
print(res)
# <callable_iterator object at 0x000002358C04DFD0>
for i in res:
    print(i)

# <re.Match object; span=(0, 0), match=''>
# <re.Match object; span=(1, 1), match=''>
# <re.Match object; span=(2, 2), match=''>
# <re.Match object; span=(3, 3), match=''>
# <re.Match object; span=(4, 4), match=''>
# <re.Match object; span=(5, 5), match=''>
# <re.Match object; span=(6, 6), match=''>
# <re.Match object; span=(7, 7), match=''>
# <re.Match object; span=(8, 8), match=''>
# <re.Match object; span=(9, 9), match=''>
# <re.Match object; span=(10, 12), match='18'>
# <re.Match object; span=(12, 12), match=''>
【8】实战
  • 获取第一页文章信息
import requests
import re

url = 'https://www.qidian.com/chapter/1031940621/705235484/'

res=requests.get(url)

with open('1.html','w',encoding='utf-8') as f:
    f.write(res.text)
  • 读取内容
with open('1.html','r',encoding='utf-8') as f:
    data=f.read()

res = re.compile( pattern=r'<p>(.*?)</p>')

res_all = re.findall(pattern=res, string=data)
for i in res_all:
    print(i)

image-20231226140527360