re模块
-
正则表达式:是一门独立的技术,任何语言都可以使用正则表达式;正则表达式时由一堆特殊的字符组合而来的。
-字符组,元字符,组合使用 -
re模块:在python中,若想使用正则表达式,必须通过re模块来实现
-
为何要使用正则表达式:当要获取一堆字符串中的某些字符时,使用正则表达式可以帮我们过滤,并提取出想要的字符数据。
-
应用场景:爬虫:re,BeautifulSoup4,Xpath,selector
数据分析过滤数据:re,pandas,numpy...
用户名与密码、手机认证:检测输入内容的合法性
使用:import re
##检测手机号码的合法性
#纯python校验
#需求:11位、开头13/14/15/19
while True:
phone_number = input('input your number:').strip()
if len(phone_number) == 11 and(phone_number.startswith(
'13'
) or phone_number.startswith(
'14'
) or phone_number.startswith(
'15'
) or phone_number.startswith(
'19'
)):
print('手机号码合法')
break
else:
print('手机号码不合法')
##re校验
#参数1:正则表达式
#参数2:需要过滤的字符串
'''
^代表开头;
$代表结束;
|代表或 (13|14):可以获取一个值,判断是否是13或14
{1}:需要获取几个值,限制数量
[]:分组限制取值范围 [0-9] 限制只能获取0-9的某一个字符
'''
import re
while True:
phone_number = input('input your number:').strip()
if re.match('^(13|14|15|19)[0-9]{9}$',phone_number):
print('合法')
break
else:
print('不合法')
'''
- 字符组:
- [0-9] 可以匹配到一个0-9的字符
- [9-0]: 报错, 必须从小到大
- [a-z]: 从小写的a-z
- [A-Z]: 从大写A-Z
- [z-A]: 错误, 只能从小到大,根据ascii表来匹配大小。
- [A-z]: 总大写的A到小写的z。
注意: 顺序必须要按照ASCII码数值的顺序编写。
'''
import re
res = re.match('[A-Za-z0-9]{9}','Lzn950919')
print(res)
print(res.group())
>>>
<_sre.SRE_Match object; span=(0, 9), match='Lzn950919'>
Lzn950919
'''
- 元字符:
*******根据博客的表格来记 (看一眼)
https://images2015.cnblogs.com/blog/1036857/201705/1036857-20170529203214461-666088398.png
- 组合使用
- \w\W: 匹配字母数字下划线与非字母数字下划线,匹配所有。
- \d\D: 无论是数字或者非数字都可以匹配。
- \t: table
- \n: 换行
- \b: 匹配单词结尾,tank jasonk
- ^: startswith
- '^'在外面使用: 表示开头。
- [^]: 表示取反的意思。
- $: endswith
- ^$: 配合使用叫做精准匹配,如何限制一个字符串的长度或者内容。
- |: 或。ab|abc如果第一个条件成立,则abc不会执行,怎么解决,针对这种情况把长的写在前面就好了,一定要将长的放在前面。
- [^...]: 表示取反的意思。
- [^ab]: 代表只去ab以外的字符。
- [^a-z]: 取a-z以外的字符。
'''
'''
re模块三种比较重要的方法:
-findall(): ------>[]
可以匹配所有字符,拿到返回的结果,列表
'qweasdqadqwf' # q
['q','q','q']
-search(): ----->obj ---->obj.group()
'qweasdqadqwf' # q
在匹配一个字符成功后,拿到结果后结束,不往后匹配。
'q'
-match():----->obj----->obj.group()
'qweasdqadqwf' # q
'q'
'wweasdqadqwf' # q
None
从匹配字符的开头匹配,若开头不是想要的内容,返回None
'''
import re
str1 = 'lzn qqq abc'
#findall
res = re.findall('[a-z]{3}',str1)
res = re.findall('[a-z]{2}',str1)
print(res)
>>>['lzn', 'qqq', 'abc'] ['lz', 'qq', 'ab']
#search
res = re.search('[a-z]{3}',str1)
print(res)
print(res.group())
>>>
<_sre.SRE_Match object; span=(0, 3), match='lzn'>
lzn
#match
res = re.match('lzn',str1)
res1 = re.match('qqq',str1)
print(res)
print(res.group())
print(res1)
>>><_sre.SRE_Match object; span=(0, 3), match='lzn'>
lzn
None