re模块

import re

x = 'hello\\world'
print(x)  ## hello\world
m = re.search('\\\\', x)
print(m)  ## <_sre.SRE_Match object; span=(5, 6), match='\\'>
n = re.search(r'\\', x)
print(n)  ## <_sre.SRE_Match object; span=(5, 6), match='\\'>
search 与 match 方法 与fullmatch方法
a=re.match(r'hello','good hello')
print(a) #None
b=re.search(r'hello','good hello')
print(b) #<_sre.SRE_Match object; span=(5, 10), match='hello'>

## 共同点:1.只对字符串查询一次2.返回值都是re.Match类型的对象
## 不同点:match从头开始匹配,一旦失败返回none;search是整个字符串匹配
## fullmatch完整匹配
y=re.fullmatch(r'hello','hello world')
x=re.fullmatch(r'hello world','hello world')
print(y) #None
print(x) #<_sre.SRE_Match object; span=(0, 11), match='hello world'>
finditer 方法  与findall方法
import re
from collections.abc import Iterable
k = re.finditer(r'x', "abcdxjshjxdfsxkhfkxjf")
print(isinstance(k, Iterable))  # True
for i in k:
    print(k)
# <callable_iterator object at 0x0000020F3C4CD240>
# <callable_iterator object at 0x0000020F3C4CD240>
# <callable_iterator object at 0x0000020F3C4CD240>
# <callable_iterator object at 0x0000020F3C4CD240>
l = re.findall(r'x', "abcdxjshjxdfsxkhfkxjf")
print(l)
# ['x', 'x', 'x', 'x']

### re.Match这个类的使用
# group 方法表示正则表达式分组
# 1 在正则表达式里使用()表示一个分组
# 2 如果没有分组,默认只有一组
# 3 分组的下标从0开始
import re

search = re.search(r'm.*f', 'hjkljdsfmgfdg')
# print(search.pos) 0
# print(search.endpos) 13
# print(search.span()) (8, 11)
# print(search.group()) mgf
# print(search.group(0)) mgf
k = re.search(r'(3.*)(5.*)(7.*9)', "sjh3fui5fjkhdf7lskh9ue")
print(k.group())  # 3fui5fjkhdf7lskh9
print(k.group(0))  # 3fui5fjkhdf7lskh9
print(k.group(1))  # 3fui
print(k.group(2))  # 5fjkhdf
print(k.group(3))  # 5fjkhdf
print(k.groups())  # 返回元组('3fui', '5fjkhdf', '7lskh9')
print(k.groupdict())  # {}
k = re.search(r'(3.*)(?P<xx>5.*)(?P<yy>7.*9)', "sjh3fui5fjkhdf7lskh9ue")
print(k.groupdict())  # 返回字典{'xx': '5fjkhdf', 'yy': '7lskh9'}
print(k.span(0))  # (3, 20)
print(k.span(1))  # (3, 7)
print(k.span(2))  # (3, 7)
print(k.span(3))  # (14, 20)
## re.compile方法的使用
import re

a = re.search(r'a.*b', '123a456b789')
print(a)

b = re.compile(r'a.*b')
c = b.search('123a456b789')
print(c)
# <_sre.SRE_Match object; span=(3, 8), match='a456b'>
# <_sre.SRE_Match object; span=(3, 8), match='a456b'>
re.I 使匹配对大小写不敏感
re.M 多行匹配,影响^和$
re.S 使.匹配包括换行在内的所有字符
\s 匹配任何空白字符
\S匹配任何非空白字符
\n
\t
\d匹配数字
\D匹配非数字
\w表示数字,字母,下划线
\W非数字,字母,下划线
()表示分组
[]表示区间
|用来表示或者
{}用来限定前面元素出现的次数
{n}
{n,}
{,n}
*0次及以上
+至少一次
?最多出现一次
^开头
$结尾
## re.sub方法
## 第一个参数:正则表达式
## 第二个参数:新字符或一个函数
## 第三个参数:需要被替换原来的字符串
import re


def test(k):
    x = int(k.group(0))
    return str(x * 2)


print(re.sub(r'\d+', test, 'fds68gfd8gf7gh89f'))
## ?尽可能少的匹配
import re

k = re.match(r'aa(\d+)', 'aa1234bc')
print(k.group(0))
j = re.match(r'aa(\d+?)', 'aa1234bc')
print(j.group(0))
-------------------------------------
import re

x5=re.match(r'aa(\d??)(.*)','aa2343ddd')
print(x5.group(0)) #aa2343ddd
print(x5.group(1)) # 空
print(x5.group(2)) #2343ddd
posted @ 2023-04-07 09:54  Bre-eZe  阅读(36)  评论(0)    收藏  举报