8.03_python_lx_day21<1>

一.正则函数

import re

(1)search   通过正则匹配出第一个对象返回,通过group取出对象中的值

1 strvar = "1+2 3*4"
2 obj = re.search("d+(.*?)d+",strvar)
3 print(obj)

返回匹配到的内容(匹配到一个就返回)

1 res = obj.group()
2 print(res) 

返回分组里面的内容,类型是元组

1 tup = obj.groups()
2 print(tup[0])

(2)match  验证用户输入内容(了解)

当search函数里面的正则表达式前面加上^ 等价于 math的用法

1 strvar = "a13566668888"
2 strvar = "13566668888"
3 obj = re.search("^d+",strvar)
4 print(obj)
5 print(obj.group())
6 obj = re.match("d+",strvar)
7 print(obj)
8 print(obj.group())

(3)split    切割

1 strvar = "alex|xboyww&wusir%ritian"
2 res = re.split("[|&%]",strvar)
3 print(res)
4 strvar = "alex234234xboyww6786wusir78967896ritian"
5 res = re.split("d+",strvar)
6 print(res)

(4)sub      替换

sub(正则,要替换的字符,原字符串[,次数])

1 strvar = "alex|xboyww&wusir%ritian"
2 res = re.sub("[|&%]","-",strvar)
3 print(res)
4 strvar = "alex|xboyww&wusir%ritian"
5 res = re.sub("[|&%]","-",strvar,2)
6 print(res)

传统replace替换的写法

1 strvar = "alex|xboyww&wusir%ritian"
2 strvar = strvar.replace("|","-").replace("&","-").replace("%","-")
3 print(strvar)

(5)subn     替换 (用法和sub一样,区别在于返回的是元组 (结果,次数)  )

1 strvar = "alex|xboyww&wusir%ritian"
2 res = re.subn("[|&%]","-",strvar)
3 res = re.subn("[|&%]","-",strvar,1)
4 print(res)

(6)finditer 匹配字符串中相应内容,返回迭代器[迭代器中包含的是对象]

1 from collections import Iterator , Iterable
2 strvar = "jkasdfjkadfjk1234asfj2342kfa"
3 it = re.finditer("d+",strvar)
4 print(isinstance(it,Iterator))

获取迭代器里面的内容

1 for i in it:
2     print(i.group())

(7)compile  指定一个统一的匹配规则

正常情况下,正则表达式编译一次,执行一次.
如果想要编译一次,多次使用的话,使用compile

compile 可以编译一次,终身受益.节省系统的资源

1 strvar = "jksdjdfsj72343789asdfaj234"
2 pattern = re.compile("d+")
3 print(pattern)
4 lst = pattern.findall(strvar)
5 print(lst)
6 obj = pattern.search(strvar)
7 print(obj.group())

二.正则表达式修饰符

(1)re.I 使匹配对大小写不敏感

1 strvar = "<h1>72347923489</H1>"
2 pattern = re.compile(r"<h1>(.*?)</h1>",flags=re.I)
3 obj = pattern.search(strvar)
4 print(obj)
5 print(obj.group())#<h1>72347923489</H1>

(2)re.M 使每一行都能够单独匹配(多行),影响 ^ 和 $

1 strvar = """<h1>72347923489</H1>
2 <p>72347923489</p>
3 <li>72347923489</li>
4 """
5 pattern = re.compile("^<.*?>(?:.*?)<.*?>$",flags=re.M)
6 lst = pattern.findall(strvar)
7 print(lst)#['<h1>72347923489</H1>', '<p>72347923489</p>', '<li>72347923489</li>']

(3)re.S 使 . 匹配包括换行在内的所有字符

1 strar = """give
2 1234234234mefive
3 """
4 pattern = re.compile("(.*?)mefive",flags=re.S)
5 obj = pattern.search(strar)
6 print(obj)
7 print(obj.group())

(4)可以加多个修饰符 通过| 拼接

1 pattern = re.compile("(.*?)mefive",flags=re.S|re.I|re.M)
原文地址:https://www.cnblogs.com/Magicianlx/p/13424091.html