python 正则表达式

import re
print("*"*20)
#re.match  在字符串开头进行匹配
pattern = "(\d+)(@)"
string = "123456@qq.com"
result = re.match(pattern,string)
print(result.group())#匹配整个group,所有的匹配项  123456@
print(result.group(0))#和上面的是一样的,匹配整个group   123456@
print(result.group(1)) # 123456
print(result.group(2)) # @

print(result.groups())  #  ('123456', '@')  返回一个元组, 元组里面是所有匹配的分组
print(result.groups()[0])
print(result.groups()[1])

"""
group()用来提出"分组"截获的"字符串",()用来分组;
groups()"匹配对象"的方法,一次性获取所有的分组,返回类型为元组。
"""

print("*"*20)
#groups 对于没有匹配到的分组返回来的是None
pattern = "(\d+)|(@)"
string = "123456@qq.com"
result = re.match(pattern,string)
print(result.groups()) #('123456', None)
print(result.groups()[0]) #123456
print(result.groups()[1])  #None

print("*"*20)
print("注意group 与groups的区别, 可以看这个例子")
pattern = "\d+"
string = "123456@qq.com"
result = re.match(pattern,string)
print(result.group()) #123456
print(result.groups())#() 没有设置分组, groups返回的就是空的元组()

print("*"*20)
pattern = "(\d+)"
string = "123456@qq.com"
result = re.match(pattern,string)
print(result.group()) #123456
print(result.groups()) # 设置分组, groups返回的就是('123456',)


print("*"*20)
#search 查找任意位置的匹配
string = "qq.com"
mo = re.compile(r"(\d+)|(@)")
mo2 = mo.search(string)
print("mo2",mo2) #  没有匹配上返回None

#re.sub  返回的是被替换之后的字符串
strings = "hello ,world,HI , world"
pattern = ","
result1 = re.sub(pattern, "", strings)
print(re.sub(pattern, "", strings)) # hello 。world。HI 。 world
print(result1) #hello 。world。HI 。 world
#re.subn  返回的是一个数组
result2 = re.subn(pattern, "", strings)
print(re.subn(pattern, "", strings)) #('hello 。world。HI 。 world', 3)  3表示替换的次数
print(result2)#('hello 。world。HI 。 world', 3) 

print("*"*20)
#编译正则表达式
print("编译正则表达式")
string2 = "123456@qq.com"
rePattern  = re.compile(r"\d+")
mo = rePattern.search(string2)
if mo is not None:
    print("mo is not Nono , match")
    print(mo.group()) # 123456
    print(mo.groups()) #()
else:
    print("can not match")

"""
findall: 从字符串任意位置查找,返回一个列表
finditer:从字符串任意位置查找,返回一个迭代器
"""
print("*"*20)
pattern3 = "\d+"
string4 = "123%456$789"
print(re.findall(pattern3, string4)) #返回一个列表  ['123', '456', '789']
print(re.finditer(pattern3, string4))# 返回一个迭代器   <callable_iterator object at 0x7fcbcbfde350>
finditerIter =  re.finditer(pattern3,string4)
for i in finditerIter:
    print(i)


#使用re.splitl 分割字符串re.split(pattern, string, maxsplit=0, flags=0)
text= "shunA1shunB2 shun shun3C"
pattern = r"\d+|\s+\|\d+\s+"
print(re.split(pattern,text))

 

posted @ 2023-02-26 20:51  朵朵奇fa  阅读(16)  评论(0编辑  收藏  举报