py09_01:正则表达式

 

 

 

 

 

单个匹配

 

 组合匹配,注意:正面的组合单独是没有意义的。必须和字符串等组合在一起。

 

 

 加了$,要么匹配成功,要么失败。而不像上图一样,匹配的不正确,但是结果却成功了

 

 

下面是两个小案例

import re

# 判断变量名是否符合规则
name = ['asdsf', '%asdf', '__!', 'a']
for i in name:
    result = re.match(r'[a-zA-Z_]+[\w]*$', i)  # $ ,指匹配到结尾,如果不加结尾符的符
    if result:
        print('变量名 【%s】 符合要求' % i)
    else:
        print('变量名 【%s】 不符合要求' % i)


# 判断邮箱是否正确
email_data = ['sdfa@126.com', 's663d@163.com', '_dsfa@163.com']  # 以字母开头,且有4-20位的163,126,gmail邮箱
for i in email_data:
    re_email = re.match(r'[a-zA-Z][a-zA-Z_$0-9]{3,19}@(163|126|gmail)\.com$', i)
    if re_email:
        print('邮箱 【%s】 符合要求' % re_email.group())
    else:
        print('邮箱 【%s】 不符合要求' % i)

 

 

import re

x = "yeyu66ronny77tom"

# res = re.sub('\d{2}', '|', x) # 把数字替换成 |
# res = re.split('\d{2}', x) # 以数字切片


res = re.search('(?P<id>\d{2})', x).group('id')
# ?P《id》 指的是定义一个名字
# 名字后面是匹配的正则。

 

 

 

posted on 2020-03-27 08:01  yeyu1314  阅读(128)  评论(0编辑  收藏  举报