python DAY_11(1) 正则表达式(1)

学习内容:
正则表达式及其使用
Tips:
1.正则表达式的相关概念
在这里插入图片描述
重点
1.正则表达式常用符号
\b匹配一个数字从0到9
\D匹配一个非数字[ ^0-9]
\s空白字符
\S非空白字符
\w字母数字字符 [A-Z]\w+(匹配多个大写字母)
\W非字母数字字符
|批量备选
?0或1次
0或多次
+1或多次
{1,3}1到三次
{n,}最多n次
{,m}最多m次
2.贪婪和非贪婪
贪婪是
***尽量匹配最大范围

非贪婪尽量匹配最小范围(方法:在量词后追加?)
3.边界匹配
^行首
s行尾
\b单词边界
\B非单词边界
\A输入开头
\z输入结尾

4.python 中寻找字符串中特定内容
findall,返回列表
1)编译法

import re
text="123 Tom is 8 years old !@#$ Nasy is 5 years old 1235 Juliy is 15 years old"
s=re.compile("\d+")
s.findall(text)
Out[6]: ['123', '8', '5', '1235', '15']

2)直接调用法

import re
text="123 Tom is 8 years old !@#$ Nasy is 5 years old 1235 Juliy is 15 years old"
re.findall("\d+",text)
Out[9]: ['123', '8', '5', '1235', '15']

这里如果遇到多个特殊符号,我们会将选区的特定内容格式前加个r

import re
text="\\123 Tom is 8 years old !@#$ Nasy is 5 years old 1235 Juliy is 15 years old"
s=re.compile("\\123")
s.findall("\\123")
Out[13]: []

我们发现输出为空
再修改之后

s=re.compile(r"\\123")
s.findall("\\123")
Out[15]: ['\\123']

3)match方法
match方法从开头位置开始

import re
text=" 123 Tom is 8 years old !@#$ Nasy is 5 years old 1235 Juliy is 15 years old"
s=re.compile(r"\d+")
s.match(text)

如果text的第一个位置是空格,就没有输出

s.match(text,1)
Out[21]: <re.Match object; span=(1, 4), match='123'>

在text后面写上1,表示从第二个位置开始查找,就有结果
4)search方法
search就克服了match的弊端

import re
text=" 123 Tom is 8 years old !@#$ Nasy is 5 years old 1235 Juliy is 15 years old"
s=re.compile(r"\d+")
s.search(text)
Out[25]: <re.Match object; span=(1, 4), match='123'>

5)finditer方法
finditer返回一个可迭代器

import re
text="123 Tom is 8 years old !@#$ Nasy is 5 years old 1235 Juliy is 15 years old"
t=s.finditer(text)
for line in t:
    print(line)
    
<re.Match object; span=(0, 3), match='123'>
<re.Match object; span=(11, 12), match='8'>
<re.Match object; span=(36, 37), match='5'>
<re.Match object; span=(48, 52), match='1235'>
<re.Match object; span=(62, 64), match='15'>

返回的是数字但是类型是字符串!

发布了33 篇原创文章 · 获赞 0 · 访问量 698

猜你喜欢

转载自blog.csdn.net/soulproficiency/article/details/103952024