59_Python正则表达式与常用函数

一、需求

  • 封装函数判断手机号码是否合法
"""
合法的手机号码:
1.长度是11位
2.数字1开头
3.全部是数字
"""

def checkPhone(tel):
    if len(tel) != 11:
        print("手机号码的长度不是11位")
        return
    if tel[0] != "1":
        print("手机号码不是数字1开头")
        return
    if not tel.isdigit():
        print("手机号码不是全部是数字...")
        return
    print("是一个合法的手机号码...")

checkPhone("1369264521")
checkPhone("23692645213")
checkPhone("1369264521a")
checkPhone("13692645213")

# 使用正则表达式验证手机号码是否合法
import re
result = re.search("^1[3-9]\d{9}$", "13692645213")
# result = re.search("^1[3-9]\d{9}$", "23692645213")
# result = re.search("^1[3-9]\d{9}$", "10692645213")
# result = re.search("^1[3-9]\d{9}$", "13692645a13")
if result:
    print("是合法的手机号码")
else:
    print("不是合法的手机号码")
  • 执行结果
手机号码的长度不是11位
手机号码不是数字1开头
手机号码不是全部是数字...
是一个合法的手机号码...
是合法的手机号码

二、正则表达式

  • 正则表达式:是一个特殊的字符序列,计算机科学的一个概念,主要用来检索/替换哪些符合某个模式的文本
  • 在python中使用正则表达式,主要是借助re模块来实现
  • 特点
    • 灵活性/功能性/逻辑性超级强
    • 可以使用极其简单的方法达到字符串的复杂控制
    • 对于刚接触的人来说有些晦涩难懂
  • 应用场景
    • 爬虫
    • 验证手机号、邮箱、身份证号等文本
    • 数据分析中的数据清洗等操作

三、常用函数

  • 导入re模块
import re
  • d:表明0-9之间的任意数字
  • +:表明前面的字符可以出现1次或多次
  • re.match 函数
"""
re.match(正则表达式, 要验证的字符串, 正则表达式的修饰符(可选参数))
作用:用于匹配字符串是否以指定的正则内容开头,匹配成功返回对象,匹配失败返回None
"""
print(re.match("\d+", "1234hello"))    # <re.Match object; span=(0, 4), match='1234'>
print(re.match("\d+", "hello1234"))    # None
  • re.search 函数
"""
re.search(正则表达式, 要验证的字符串, 正则表达式的修饰符(可选参数))
作用:用于匹配字符串中是否包含指定的正则内容,匹配成功返回对象,匹配失败返回None
"""
print(re.search("\d+", "9876hello"))    # <re.Match object; span=(0, 4), match='9876'>
print(re.search("\d+", "hello9876"))    # <re.Match object; span=(5, 9), match='9876'>
print(re.search("\d+", "hel9876lo"))    # <re.Match object; span=(3, 7), match='9876'>
print(re.search("\d+", "hello"))    # None
  • re.findall 函数
"""
re.findall(正则表达式, 要验证的字符串)
作用:使用正则表达式获取匹配成功的数据,匹配成功返回的是一个列表
"""
print(re.findall("\d+", "hello123world987welcome3232"))    # ['123', '987', '3232']
print(re.findall("\d+", "helloworld"))    # []
© 版权声明

相关文章

暂无评论

none
暂无评论...