python 正则表达式

python 正则表达式示例:

 1 #re.py
 2 import re
 3 
 4 '''
 5 m = re.match(r'^\d{3}\-\d{3,8}$', '010-12345')
 6 print(m.group(0))
 7 
 8 test = '正则表达式'
 9 if re.match(r'正则表达式', test):
10     print('ok')
11 else:
12     print('failed')
13 
14 #吧字符串切分成规则的list
15 s = 'a b   c'.split(' ')
16 print(s)
17 
18 l = re.split(r'\s+', 'a b  c')
19 print(l)
20 
21 l = re.split(r'[\s\,]+', 'a,b, , ,c')
22 print(l)
23 
24 #编译,生成一个规则,用来处理目标字符串
25 #group()返回匹配结果,0:原始字符串,1、2....按顺序返回匹配到的结果
26 re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
27 #使用
28 #s=re_telephone.match('010-12345').groups()
29 s=re_telephone.match('010-12345')
30 print(s.group(0))
31 print(s.group(1))
32 print(s.group(2))
33 '''
34 
35 import re
36 def is_valid_email(addr):
37 #    str=r'^[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+){0,4}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}$'
38     str=r'^[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+){0,4}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){1,4}$'
39     if re.match(str, addr):
40         return True
41 
42 print(is_valid_email('a@szclou.com'))
43 print(is_valid_email('###aaaa.aaa@szclou.com.org'))
44 
45 #IPv4匹配公式 (?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))
46 #ipv6匹配公式 ^([\\da-fA-F]{1,4}:){7}([\\da-fA-F]{1,4})$
47 
48 #https://docs.python.org/3/library/re.html?highlight=re#module-re

 

posted on 2018-08-08 09:31  mofei004  阅读(110)  评论(0编辑  收藏  举报

导航