python正则一篇搞掂( 四 )

3.4 S
匹配任何非空白字符
s = 'fdfa**68687+ 我怕n fdgtf_dn'a = re.findall('S', s)print(a)
运行结果:
['f', 'd', 'f', 'a', '', '', '6', '8', '6', '8', '7', '+', '我', '怕', 'n', 'f', 'd', 'g', 'f', '_', 'd']3.5 w
匹配除符号外的单个字母 , 数字 , 下划线或汉字等
a = re.findall("w", s)print(a)运行结果:
 

  • ['f', 'd', 'f', 'a', '6', '8', '6', '8', '7', '我', '怕', 'n', 'f', 'd', 'g', 'f', '_', 'd']
  元字符说明 .匹配除换行符以外的任意字符w匹配字母或数字或下划线W和 w 相反d匹配数字D和 d 相反s匹配任意的空白符S和 s 相反 小案例
  1. 检测邮箱
s = "3003756995@qq.com"a = re.findall('^w+@w+.com$', s) # 检测邮箱if a:print('是正确格式的邮箱')else:print('不是邮箱地址') output:
  • 是正确格式的邮箱
  • 检测手机号码
s = '13812345678'r = re.findall('^1[3-9]d{9}$', s)# 检查手机号码if r:print('手机号码格式正确')else:print('手机号码格式不正确')output: 
 手机号码格式正确4.re 模块常用函数
4.1 re.match 
    •  
    re.match(pattern, string, flag)
    • 尝试从字符串的起始位置匹配一个模式 , 成功返回匹配对象 , 否则返回 None
    • pattern: 正则表达式
    • string: 被匹配的字符串
    • flag: 标志位 , 表示匹配模式
import reurl = 'www.hhxpython.com'res = re.match('www', url)# 'www' 就是正则表达式 , 没有元字符表示匹配字符本身# re.match默认是从字符串开头匹配 , 等价于'^www'print(res)运行结果:
 <re.Match object; span=(0, 3), match='www'>res2 = re.match('hhx', url)print(res2)运行结果:
 
  • None
匹配对象
match 函数返回一个匹配对象 , 通过这个对象可以取出匹配到的字符串和分组字符串
 line = 'Good good study, Day day up!'match_obj = re.match('(?P<aa>.*), (.*) (.*)', line)if match_obj: print(match_obj.group())# 返回匹配到的字符串print(match_obj.group(1))# 返回对应序号分组字符串 从1开始print(match_obj.group(2))print(match_obj.group(3))else:print('not found')print(match_obj.groups())# 返回分组字符串元组print(match_obj.groupdict())# 按照分组名和分组字符串组成字典 (?P<name>pattern) 运行结果:
Good good study, Day day up!Good good studyDay dayup!('Good good study', 'Day day', 'up!'){'aa': 'Good good study'}4.2 re.search
    •  
    re.search(pattern, string, flag)
    • 扫描整个字符串返回第一个成功的匹配对象
    • pattern: 正则表达式
    • string: 被匹配的字符串
    • flag: 标志位 , 表示匹配模式
url = 'www.hhxpython.com'res = re.search('www', url)# 'www' 就是正则表达式 , 没有元字符表示匹配字符本身print(res)运行结果:
<re.Match object; span=(0, 3), match='www'> res2 = re.search('hhx', url)print(res2)运行结果:
<re.Match object; span=(4, 7), match='hhx'>


推荐阅读