Home > other >  Regular expressions:
Regular expressions:

Time:11-02

''' 正则表达式 ''''''re模块是内置的可以直接导入'''import re'''re.match()从字符串起始的位置开始匹配 re.search()扫描整个字符串返回第一个成功的匹配'''text='hello-34455'ret1=re.match('he', text) # 匹配某个字符ret2=re.match('.', text) # . 匹配任意字符,单匹配不到换行符ret3=re.match('\d', text) # \d 等同于[0-9] 即匹配任意数字0-9ret4=re.match('\D', text) # \D 匹配任意非数字ret5=re.match('[hel]', text) # [] 组合的方式只要满足中括号里边的就可匹配text1='234-98557kjhuhhj'ret6=re.search('[^\d\-]+', text1) # + 匹配多个 ^取反print (ret6.group())'''匹配手机号码'''# text=input("请输入正确的手机号:")# ret=re.match("1[3589]\d{9}",text)#电话号码是以1开头第二个数字可能是3,5,8,9后边的就位是0-9任意的# print (ret.group())#提取匹配到的字符串'''验证邮箱'''# text=input("请输入正确的邮箱:")# ret=re.match("\d{9}@[0-9a-z]+\.com",text)#邮箱前九位是随意的0-9的数字然后是@和0-9或a-z最后是.com# print (ret.group())'''验证URL'''# text=input("请输入正确的url:")# ret=re.match("(http|https|ftp)://[\S]+",text)#'|'代表的是或的意思 \S([^\s])匹配的是非空白# print (ret.group())'''匹配0-100之间的数'''# text=input("请输入0-100之间的数包括0和100:")# ret=re.match("[1-9]\d? $| 100 ", the text) is or # '|' mean? Representative of greed pattern # print (ret) group ())
  • Related