一、扫描整个字符串并返回:re.search+group

import re

line = "Cats are smarter than dogs"

matchObj = re.search(r'(.*) are (.*?) .*', line, re.M | re.I)   # re.I表示忽略大小写,re.M表示多行匹配,影响 ^ 和 $

if matchObj:
    print("matchObj.group() : ", matchObj.group())   # 匹配元素
    print("matchObj.group(0) : ", matchObj.group(0))  # 匹配元素
    print("matchObj.group(1) : ", matchObj.group(1))    #匹配第1个小组
    print("matchObj.group(2) : ", matchObj.group(2))    #匹配第2个小组
    print("matchObj.groups() : ", matchObj.groups())    #匹配所有小组
else:
    print("No match!!")

打印:

matchObj.group() : Cats are smarter than dogs
matchObj.group(0) : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
matchObj.groups() : ('Cats', 'smarter')

 

二、检索和替换re.sub

 

import re 

phone = "2004-959-559 # 这是一个国外电话号码"

num = re.sub(r'#.*$', "", phone) # .*表示匹配所有字符,$表示结尾
print "电话号码是: ", num
num = re.sub(r'\D', "", phone) # \d表示匹配数字,\D非数字
print "电话号码是 : ", num

打印:

电话号码是:  2004-959-559 
电话号码是 :  2004959559

三、分割:re.split

 

import re
s = 'cheney, daicy, lucy.'
s_new1 = re.split('\W+', s) # 不包含分割符
print(s_new1)
s_new2 = re.split('(\W+)', s) # 包含分割符
print(s_new2)
s_new3 = re.split('\W+', s, 1) # 只分割一次
print(s_new3)

打印:

['cheney', 'daicy', 'lucy', '']
['cheney', ', ', 'daicy', ', ', 'lucy', '.', '']
['cheney', 'daicy, lucy.']

四、分组匹配转字典:(?P...)+groupdict()

 

import re
s = '1102231990xxxxxxxx'
res = re.search('(?P<province>\d{3})(?P<city>\d{3})(?P<born_year>\d{4})',s)
print(res.groupdict())

打印:{'province': '110', 'city': '223', 'born_year': '1990'}

五、模式元素含义

^:匹配字符串的开头

$:匹配字符串的末尾

.:匹配任意字符,除了换行符

[amk]: 匹配 'a','m'或'k'

[^amk]:匹配 'a','m'或'k' 之外的字符

*:匹配0个或多个的表达式

+:匹配1个或多个的表达式

?:匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式

\w:匹配字母数字及下划线

\W:匹配非字母数字及下划线

\s:匹配任意空白字符,等价于 [ \t\n\r\f]

\d:匹配任意数字,等价于 [0-9].

w:匹配字母数字及下划线

w:匹配字母数字及下划线

w:匹配字母数字及下划线

六、实例:

a.*?b:匹配最短的以a开头b结束的字符串,比如aabab,可以匹配到aab和ab

^[0-9].*[0-9]$:匹配以数字开头和结尾的字符串,中间任意

import re

mobile = '18312423454'
# 3种符合条件情况:
#   13、15、18开头11位数字
#   147开头11位
#   179开头11位          
MOBILE = "^1[358]\d{9}$|^147\d{8}$|^179\d{8}$"  

if re.match(MOBILE,mobile):
    print(mobile)