这些正则你都知道吗?

这些正则你都知道吗?

匹配的边界

符号含义
^匹配开头
$匹配结尾

各种符号的表示

符号含义
.匹配出\n职位的任意一种字符
\d匹配任意一个数字0-9,相当于[0-9]
\D匹配任意一个非数字,相当于[^0-9]
\w匹配任意一个数字,字母和下划线相当于[0-9a-zA-Z_]
\W匹配任意一个非(数字,字母和下划线)相当于[^0-9a-zA-Z_]
\s匹配任意一个空白,例如:\t,\n,\r,空格等
\S匹配任意一个非空白
[]匹配括号内中字符的任意一个:[abc],匹配a或者b或者c
[^abc]匹配除了(a,b,c)之外的任意一个字符
^[a,b,c]匹配以a/b/c开头的任意一个字符

重复次数的符号

符号含义
*匹配前一个字符任意次数,0或多次
?匹配前一个字符0次或多次,最多一次
+匹配前一个字符1次或多次,最少一次
{n}匹配前一个字符n次
{n,}匹配前一个字符至少n次
{n,m}匹配前一个字符n-mci

正则表达式修饰符-可选标志

修饰符描述
re.l使匹配对大小写不敏感
re.L做本地化识别(locale-aware)匹配
re.M多行匹配,影响 ^ 和 $
re.S使 . 匹配包括换行在内的所有字符
re.U根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。

正则的一些方法

compile:指定规则

pattern=re.compile()

match():从头匹配

match(‘待匹配的字符串’,[起始索引,结束索引])

定义:
  • 从头开始匹配,如果开头的字符不符合匹配规则,直接返回None
  • 如果匹配成功,返回的是match对象
  • 如果没有匹配成功,返回None
示例:
import re

str = '123hello456world'
match_pattern = re.compile(r'\d+')
result = match_pattern.match(str)
result = match_pattern.match(str,8,12)
print(result)  # <_sre.SRE_Match object; span=(0, 3), match='123'>这是match对象

group():分组

定义:
  • 如果要进行分组,必须使用()来进行分组

  • 可以使用group(n)来获取对应组的内容,n是从1开始

  • 可以使用group()获取匹配成功的内容

示例:
import re

group_str = '123hello123world'
match_pattern = re.compile(r'\d+')
result = match_pattern.match(group_str)
print(result.group())  # 123

group_str = '1h2e3lloworld'
pattern = re.compile(r'(\d)h(\d)e(\d)')
result = pattern.match(group_str)
print(result.group())  # 1h2e3
print(result.group(1))  # 1
print(result.group(2))  # 2
print(result.group(3))  # 3
print(result.group(0))  # 1h2e3
扩展:分组的反向引用
注意:

​ 反向引用代表分组,只是前面的分组的值的引用

import re

html = '<html><h1>helloworld</h1></html>'
pattern = re.compile(r'<(html)><(h1)>(.*)</\2></\1>')
result = pattern.match(html)
print(result.group())  # <html><h1>helloworld</h1></html>
print(result.group(1))  # html
print(result.group(2))  # h1
print(result.group(3))	# helloworld
print(result.group(4))  # 报错

span():

作用:

​ 查看匹配成功的自传的索引范围

示例:
import re

span_str = '1h2e3lloworld'
pattern = re.compile(r'(\d)h(\d)e(\d)')
result = pattern.match(span_str)
print(result.span())  # (0, 5)
print(result.span(2))  # (2, 3)

search(): 全局匹配

search(‘待匹配的字符串’[,起始索引,结束索引]) 全局匹配,只匹配成功一次

定义:
  • 返回match对象
  • 如果开头不符合匹配规则,继续向下匹配
  • 直到整个字符串中都没有找到符合规则的时候,返回None
示例:
import re

search_str = '1h2e3h2e3lloworld'
pattern = re.compile(r'\d')
result = pattern.search(search_str)
print(result) #  <_sre.SRE_Match object; span=(0, 1), match='1'>
print(result.group())  # 1

search_str = 'h2e3lloworld'
pattern = re.compile(r'\d')
result = pattern.search(search_str)
print(result) #  <_sre.SRE_Match object; span=(1, 2), match='1'>
print(result.group())  # 2

findall(): 全局匹配

定义:
  • 所有符合条件的子串,全部返回,返回的是一个列表,列表中的元素是匹配成功的内容
  • 列表中元素不是match对象
  • 如果没有符合条件的子串,返回的是一个空列表
示例:
import re

findall_str = '1h2e3lloworld'
findall_str2 = 'helloworld'
pattern = re.compile('\d')
result = pattern.findall(findall_str)
result2 = pattern.findall(findall_str2)
print(result)  # ['1', '2', '3']
print(result2)  # []

finditer(): 全局匹配

定义:
  • 如果匹配成功,返回的是可迭代的对象,可迭代对象中,包含所有匹配成功的match对象
示例:
import re

finditer_str = '1h2e3lloworld'
pattern = re.compile('\d')
result = pattern.finditer(finditer_str)
print(result)  # <callable_iterator object at 0x000000000288E710>
for i in result:
    print(i)  # match对象
    print(i.group())

split(): 切割方法,返回列表

splie(‘待切割的字符串’,[maxsplit])

示例:
import re

split_str = 'a,b,c;d e'
pattern = re.compile(r'[,; ]') # []里面的任意一个字符
result = pattern.split(split_str)
print(result)  # ['a', 'b', 'c', 'd', 'e']

# 可以使用maxsplit指定最大的切割次数
result = pattern.split(split_str,maxsplit=2)
print(result)  # ['a', 'b', 'c;d e']

sub(): 替换方法

sub(‘新的字符串’,'旧的字符串)

第一种方法:
import re

sub_str = 'hello 123,hello 456'
pattern = re.compile(r'(\w+) (\d+)')
result = pattern.sub('hi world',sub_str)
print(result)  # hi world,hi world

第二种方法:使用函数

sub(‘函数名’,‘旧的字符串’)

对函数的要求:
  • 函数必须要有形式参数,参数作用:代表匹配到的子串
  • 函数必须要有返回值,返回值必须是字符串类型,返回值作用:代表新的字符串
import re

sub_str = 'hello 123,hello 456'
pattern = re.compile(r'(\w+) (\d+)')
def func(m):
    print(m)
    return 'hi ' + m.group(2)
result = pattern.sub(func,sub_str)
print(result)  # hi 123,hi 456

re的四个方法的区别和共同点

方法使用方法描述
matchre.match(pattern, string[, flags])从首字母开始开始匹配,string如果包含pattern子串,则匹配成功,返回Match对象,失败则返回None,若要完全匹配,pattern要以$结尾。
searchre.search(pattern, string[, flags])若string中包含pattern子串,则返回Match对象,否则返回None,注意,如果string中存在多个pattern子串,只返回第一个。
findallre.findall(pattern, string[, flags])返回string中所有与pattern相匹配的全部字串,返回形式为数组。
finditerre.finditer(pattern, string[, flags])返回string中所有与pattern相匹配的全部字串,返回形式为迭代器。

贪婪模式和非贪婪模式

贪婪模式:尽可能多的获取 .*

import re

html = '<div>hello</div><div>world</div><div>python</div><div>java</div>'
# 贪婪模式:尽可能多的获取   .*
pattern = re.compile(r'<div>(.*)</div>')
result = pattern.findall(html)
print(result) # ['hello</div><div>world</div><div>python</div><div>java']

非贪婪模式:尽可能少的匹配

html = '<div>hello</div><div>world</div><div>python</div><div>java</div>'
# 非贪婪模式:尽可能少的匹配
pattern = re.compile(r'<div>(.*?)</div>')
result = pattern.findall(html)
print(result)  # ['hello', 'world', 'python', 'java']

爬虫的万能表达式:

.*?(非贪婪模式) 需要配合边界值使用

re.compile(r’<边界>(.*?)</边界>,re.S) # 无敌表达式,匹配万物

匹配中文:

中文编码:[\u4e00-\u9fa5]

cn_str = 'hello 你好 world 世界'
pattern = re.compile(r'[\u4e00-\u9fa5]+')
res = pattern.findall(cn_str)
print(res)  # ['你好','世界']
  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值