文章目录
正则表达式
一. 相关函数
1. re.match():
-
原型:
match(pattern, string, flags=0) -
参数:
- pattern:
匹配的正则表达式
- string :
要匹配的字符串
- flags:
标志位,用于控制正则表达式的匹配方式,值如下:
- re.I: 忽略大小写
- re.L: 做本地户识别
- re.M: 多行匹配,影响^和$
- re.S: 是 . 匹配包括换行符在内的所有字符
- re.U: 根据Unicode字符集解析字符,影响\w \W \b \B
- re.X: 使我们以更灵活的格式理解正则表达式
- pattern:
-
功能:尝试从字符串的起始位置匹配一个模式,如果不是
起始位置匹配成功的话,返回None -
code:
print(re.match("www","wwW.baidu.com",flags=re.I)) -
result:
<re.Match object; span=(0, 3), match='wwW'>
2. re.search():
- 原型:
search(pattern, string, flags= 0) - 参数:同上述
re.match() - 功能:扫描整个字符串,并返回第一个成功的匹配
- code:
print(re.search("chu", "you're chu!", flags=re.I)) - result:
<re.Match object; span=(7, 12), match='chu'>
3. re.findall():
- 原型:
findall(pattern, string, flags= 0) - 参数:同上述
re.match() - 功能:扫描整个字符串,并返回结果列表
- code:
print(re.findall("chu", "you're chu!chu a man", flags=re.I)) - result:
['chu', 'chu']
4. re.split():
- 原型:
split(pattern, string, maxsplit=0, flags=0) - 参数:部分同上述
re.match()
maxsplit是分离的次数,maxsplit=1
即分离一次,默认为0,不限制次数 - 功能:通过正则表达式将字符串分离。如果用括号将正则表达
式括起来,那么匹配的字符串也会被列入到list中返回 - code:
str1 = "you're a fat man!" print(re.split(r" +",str1),3) - result:
["you're", 'a', 'fat', 'man!'] 3
5. re.finditer():
- 原型:
finditer(pattern, string, flags= 0) - 参数:同上述
re.match() - 功能:扫描整个字符串,返回的是一个迭代器
- code:
注:StopIteration不要忘str3 = "chu is a man,chu is a fat man,chu is a nice man" d = re.finditer(r"chu", str3) while True: try: l = next(d) print(d) except StopIteration as e: break - result:
<callable_iterator object at 0x000001AC7B04A4C0> <callable_iterator object at 0x000001AC7B04A4C0> <callable_iterator object at 0x000001AC7B04A4C0>
6. re.sub() 和 re.subn():
- 原型:
sub(pattern, repl, string, count=0, flags=0)
subn(pattern, repl, string, count=0, flags=0) - 参数:
- pattern: 正则表达式
- repl: 指定的用来替换的字符串
- string: 目标字符串
- count: 最多替换次数
- flag: 同上
- 功能:在目标字符串中找到正则表达式的规则匹配字符串,把他们替换成
指定的字符串。可以指定替换的次数,如果不指定,替换所有的匹
配字符串 - code:
str5 = "sunck is a nice nice nice man" print(re.sub(r"nice","good",str5)) #sub()返回的是字符串 print(re.subn(r"nice","good",str5)) #subn()返回的是元组 - result:
sunck is a good good good man ('sunck is a good good good man', 3)
二. 匹配单个字符或数字
1. 元字符
-
.(英文句点) 匹配除换行符以外的任意字符
-
[123456] [ ]是字符集合,表示匹配方括号中所包含的任意一个字符
[a-z] 匹配任意小写字母
[0-9a-zA-Z] 匹配任意字母和数字
- [^chu] 匹配除s、u、n、c、k以外的所有字符
注:^称为脱字符,表示不匹配集合中的字符 - \d 匹配所有数字
\D 匹配所有非数字 - \w 匹配数字、字母和下划线
\W 匹配非数字、字母和下划线 - \s 匹配任意的空白符(空格、换行、回车、换页、制表
\S 同理
2. code
print(re.findall("\w", "_chu is a man 3" ))
print(re.findall("\s", "_chu is a man 3" ))
print(re.findall("\d", "_chu4 is a man 3" ))
print(re.findall("[a-d1-5]", "_chu is a man 3" ))
运行结果
['_', 's', 'u', 'n', 'c', 'k', 'i', 's', 'a', 'p', 'i', 'g', '3']
[' ', ' ', ' ', ' ']
['4', '3']
['c', 'a', '3']
三. 匹配多个字符或数字
1. 又一些元字符(边界字符)
- ^ 行首匹配,和在[ ]里的^不是一个意思
- $ 行尾匹配
- \A 匹配字符串开始,与^的区别,前者只匹配整个字符串的开头,
即使在re.M模式下也不会匹配他行的行首 - \Z 匹配字符串结束,与$的区别,前者只匹配整个字符串的结束,
即使在re.M模式下也不会匹配他行的行尾 - \b 匹配一个单词的边界,也就是值单词和空格间的位置
注:'er\b’可以匹配never,不能匹配nerve - \B 匹配非单词边界
2.又一些code
print(re.search("^chu", "chu is a man" ))
print(re.search("man$", "chu is a man" ))
print(re.findall("\Achu", "chu is a man\nchu is a man" ))
print(re.findall("man\Z", "chu is a man\nchu is a man" ))
# r 为转义符
print(re.search(r"er\b","never"))
print(re.search(r"er\b","nerve"))
print(re.search(r"er\B","never"))
print(re.search(r"er\B","nerve"))
运行结果
<re.Match object; span=(11, 14), match='man'>
['chu']
['man']
<re.Match object; span=(3, 5), match='er'>
None
None
<re.Match object; span=(1, 3), match='er'>
3. 又又一些元字符
说明:下方的x、y、z均为假设的普通字符,不是正则表达式的元字符
- (xyz) 匹配小括号内的xyz(作为一个整体去匹配)
- x? 匹配0个或者1个x
- x* 匹配0个或者任意多个x(.* 表示匹配0个或者任意多个字符
(换行符除外)) - x+ 匹配至少1个x
- x{n} 匹配确定的n个x(n是一个非负整数)
- x{n,} 匹配至少n个x(n是一个非负整数)
- x{n,m} 匹配至少n个x最多m个x(n是一个非负整数,n小于等于m)
- x|y | 表示或,匹配的时x或y
4. 又又一些code
print(re.findall(r"(chu)", "chugood is a man,chu is a man" ))
print(re.findall(r"a?", "aaabbaaba" )) # 非贪婪匹配(尽可能少的匹配)
print(re.findall(r"a*", "aaabbaaba" )) # 贪婪匹配(尽可能多的匹配)
print(re.findall(r"a+", "aaabbaaba" )) # 贪婪匹配
print(re.findall(r"a{3}", "aaabbaaba" ))
print(re.findall(r"a{3,}", "aaabbaabaaaa" )) # 贪婪匹配
print(re.findall(r"a{3,5}", "aaabbaabaaaa" )) # 贪婪匹配
print(re.findall(r"((c|C)hu)", "chugood is a man,Chu is a man" )) # 贪婪匹配
运行结果
['chu', 'chu']
['a', 'a', 'a', '', '', 'a', 'a', '', 'a', '']
['aaa', '', '', 'aa', '', 'a', '']
['aaa', 'aa', 'a']
['aaa']
['aaa', 'aaaa']
['aaa', 'aaaa']
[('chu', 's'), ('chu', 'S')]
四. 提取子串
1. 概念:
除了简单的判断是否匹配之外,正则表达式还有提取子串的功能;用 () 表示的就是提取分组,举例如下:
str6 = "sunck is a good man!sunck is a nice man!sunck is a handsome man!"
str7 = "010-53247654"
# 使用格式 ?P<组名> 添加标题
m = re.match(r"(?P<first>\d{3})-(?P<last>\d{8})", str7)
# 使用序号获取对应组的信息,group(0)一直代表的原始字符串
print(m.group(0))
print(m.group("first"))
print(m.group(1))
print(m.group(2))
# 查看匹配的各组的情况
print(m.groups())
代码结果:
010-53247654
010
010
53247654
('010', '53247654')
五. 相关实例
1. 需求:提取chu……man
str = "chu is a good man!chu is a nice man!chu is a very hansome man"
# 注意两种不同匹配模式得到的结果
re1 = r"^chu.*man$"
re2 = r"chu.*?man"
print(re.findall(re1, str))
print(re.findall(re2, str))
运行结果
['chu is a good man!chu is a nice man!chu is a very hansome man']
['chu is a good man!', 'chu is a nice man!']
来源:CSDN
作者:夏至未至c
链接:https://blog.csdn.net/qq_43364352/article/details/104280919