什么是正则表达式
正则表达式就是记录文本规则的代码
基本用法
\: 将下一个字符标记为一个特殊字符.
d # 普通字符
\d # 0-9 正整数
s # 普通字符
\s # 空白符,比如\t,\n
1、定界符
^: 匹配输入字符串的开始位置
$: 匹配输入字符串的结束位置
正则: ^123.*123$ # 匹配123hello123
\b: 匹配一个单词边界,也就是指单词和空格间的位置
teacher Li
正则: er\b # 可以匹配出er
\B: 匹配非单词边界
verb
正则: er\B # 可以匹配出er
2、个数/次数
*: 匹配前面的子表达式零次或多次
+: 匹配前面的子表达式一次或多次
?: 匹配前面的子表达式零次或一次
{n}: n 是一个非负整数
{n,}: n 是一个非负整数
{n,m}: m 和 n 均为非负整数,其中n <= m
heo helo hello helllo
正则: hel*o # 可以匹配 heo helo hello helllo
正则: hel+o # 可以匹配 helo hello helllo
正则: hel?o # 可以匹配 heo helo
正则: hel{3}o # 可以匹配 helllo
正则: hel{1,}o # 可以匹配 helo hello helllo
正则: hel{0,3}o # 可以匹配 heo helo hello helllo
?: 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的
hel hell helll
正则: hel+ # 可以匹配 hel hell helll
正则: hel+? # 只会匹配 hel hell helll中的 hel部分
.: 匹配除 “\n” 之外的任何单个字符
hello world python
正则: .* # 可以匹配出所有单词
x|y: 匹配 x 或 y
hello aello
正则: a|hello # 匹配 hello 和 a
正则: [a|h]ello # 匹配 hello 和 aello
3、范围
[xyz]: 字符集合
[^xyz]: 字符集合取反(非xyz的其余任意字符,不仅限于其余23个小写字母)
[a-z]: 字符范围
[^a-z]: 负值字符范围(非a-z的其余任意字符,而不仅限于大写字母)
4、空白符
\f: 匹配一个换页符
\n: 匹配一个换行符
\r: 匹配一个回车符
\t: 匹配一个制表符
5、语法糖
\d: 匹配一个数字字符. 相当于 [0-9]
\D: 匹配一个非数字字符. 相当于 [^0-9]
\s: 匹配任何空白字符,包括空格、制表符、换页符等等. 相当于 [\f\n\t\r\v]
\S: 匹配任何非空白字符. 相当于 [^\f\n\t\r\v]
\w: 匹配字母、数字、下划线. 相当于 [A-Za-z0-9_]
\W: 匹配非字母、数字、下划线. 相当于 [^A-Za-z0-9_]
re模块
Python中使用re模块来实现正则表达式匹配
1、编译正则表达式模式
re.compile
编译正则表达式模式,返回一个对象的模式。(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率。)
格式:
re.compile(pattern,flags=0)
pattern: 编译时用的表达式字符串。
flags 编译标志位,用于修改正则表达式的匹配方式,如:是否区分大小写,多行匹配等。常用的flags有:
re.S(DOTALL)
使.匹配包括换行在内的所有字符
re.I(IGNORECASE)
使匹配对大小写不敏感
re.L(LOCALE)
做本地化识别(locale-aware)匹配,法语等
re.M(MULTILINE)
多行匹配,影响^和$
re.X(VERBOSE)
该标志通过给予更灵活的格式以便将正则表达式写得更易于理解
re.U
根据Unicode字符集解析字符,这个标志影响\w,\W,\b,\B:
举例1:
import re
tt = "Tina is a good girl, she is cool, clever, and so on..."
rr = re.compile(r'\w*oo\w*')
print(rr.findall(tt)) #查找所有包含'oo'的单词
执行结果如下:
['good', 'cool']
举例2:
import re
a = '''asdfsafhellopass:
worldafdsf
'''
b = re.findall('hello(.*?)world',a)
c = re.findall('hello(.*?)world',a,re.S)
print 'b is ' , b
print 'c is ' , c
执行结果如下:
b is []
c is ['pass:\n\t234455\n\```
2、查找
1)re.match
re在字符串刚开始的位置开始进行匹配。
//注:这个方法并不是完全匹配。当pattern结束时若string还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符’$’
格式:
re.match(pattern, string, flags=0)
举例:
print(re.match('com','comwww.runcomoob').group())
print(re.match('com','Comwww.runcomoob',re.I).group())
执行结果如下:
com
com
2)re.search
re.search函数会在字符串内查找模式匹配,只要找到第一个匹配然后返回,如果字符串没有匹配,则返回None。
与re.match不同之处在于:
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
格式:
re.search(pattern, string, flags=0)
举例:
print(re.search('\dcom','www.4comrunoob.5com').group())
执行结果如下:
4com
注:
match和search一旦匹配成功,就是一个match object对象,而match object对象有以下方法:
group() 返回被 RE 匹配的字符串
start() 返回匹配开始的位置
end() 返回匹配结束的位置
span() 返回一个元组包含匹配 (开始,结束) 的位置
常用的是:group(),其中:
1、group()
返回re整体匹配的字符串;
2、group (n,m) 返回组号为n,m所匹配的字符串,
如果组号不存在,则返回indexError异常
(可以一次输入多个组号,对应组号匹配的字符串)
3、groups() 方法返回一个包含正则表达式中所有小组字符串的元组
举例:
>>> import re
>>> test_string = '123456AAA987654BBB456789'
>>> pattern = re.compile('([1-9]*)AAA([1-9]*)BBB([1-9]*)')
>>> result = re.match(pattern, test_string)
>>> result
<re.Match object; span=(0, 24), match='123456AAA987654BBB456789'>
>>> result.group()
'123456AAA987654BBB456789'
>>> result.group(0)
'123456AAA987654BBB456789'
>>> result.group(1)
'123456'
>>> result.group(2)
'987654'
>>> result.group(3)
'456789'
>>> result.group(1,3)
('123456', '456789')
>>> result.group(1,2,3)
('123456', '987654', '456789')
>>> result.groups()
('123456', '987654', '456789')
3)re.findall
re.findall遍历匹配,可以获取字符串中所有匹配的字符串,返回一个列表。
格式:
re.findall(pattern, string, flags=0)
举例:
import re
test_string = 'hello'
result = re.findall('l', test_string)
print(result)
运行结果:
['l', 'l']
3、正则匹配分割字符串
按照能够匹配的子串将string分割后返回列表。
可以使用re.split来分割字符串,如:re.split(r’\s+’, text);将字符串按空格分割成一个单词列表。
格式:
re.split(pattern, string[, maxsplit])
maxsplit用于指定最大分割次数,不指定将全部分割。
举例:
print(re.split('\d+','one1two2three3four4five5'))
执行结果如下:
['one', 'two', 'three', 'four', 'five', '']
4、替换
re.sub
使用re替换string中每一个匹配的子串后返回替换后的字符串。
格式:
re.sub(pattern, repl, string, count)
举例1:
import re
test_string = 'hello'
result = re.sub('l', 'm', test_string)
print(result)
运行结果:
hemmo
举例2:
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+', '-', text))
执行结果如下:
JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...
其中第二个函数是替换后的字符串;本例中为'-'
第四个参数指替换个数。默认为0,表示每个匹配项都替换。
re.sub还允许使用函数对匹配项的替换进行复杂的处理。
如:re.sub(r’\s’, lambda m: ‘[’ + m.group(0) + ‘]’, text, 0);将字符串中的空格’ ‘替换为’[ ]’。
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+', lambda m:'['+m.group(0)+']', text,0))
执行结果如下:
JGood[ ]is[ ]a[ ]handsome[ ]boy,[ ]he[ ]is[ ]cool,[ ]clever,[ ]and[ ]so[ ]on...
subn()
返回替换次数
格式:
subn(pattern, repl, string, count=0, flags=0)
举例:
print(re.subn('[1-2]','A','123456abcdef'))
print(re.sub("g.t","have",'I get A, I got B ,I gut C'))
print(re.subn("g.t","have",'I get A, I got B ,I gut C'))
执行结果如下:
('AA3456abcdef', 2)
I have A, I have B ,I have C
('I have A, I have B ,I have C', 3)
其他:
1、在正则表达式中,’要匹配一个\,你需要写四个\作为匹配特征,其中\是正则写法,而在字符串中又要对\分别进行转义,也就是需要四个\。
参考:
http://f61be319.wiz03.com/share/s/3S6-cp1BIQ952yXKyj02PIM41OJFbm3QOkPd20LY0Q2m8zw_