正则表达式-re模块的使用

正则表达式的基本使用

一、re模块

正则表达式是用来匹配处理字符串的。

python 中使用正则表达式需要引入re模块。

import re

二、search()和match()的区别

match()函数只检测字符是不是在string的开始位置匹配;search()会扫描整个string查找匹配。

也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none。

>>> import re
>>> a = 'hello world'
>>> b = re.search('w',a)
>>> b
<_sre.SRE_Match object; span=(6, 7), match='w'>
>>> b.group()
'w'
>>> c = re.match('w',a)
>>> c
>>> d = re.match('h',a)
>>> d
<_sre.SRE_Match object; span=(0, 1), match='h'>
>>> d.group()
'h'
>>>

三、通配符

字符

描述

.

匹配除换行符 \n 之外的任何单字符

*

匹配前一个字符出现0次或者无数次,至少0次 贪婪(至多)匹配

+

匹配前一个字符出现一次或者无数次,至少1次 贪婪(至多)匹配

\d

匹配数字,默认只匹配一个

\D

匹配非数字,默认只匹配一个

\s

匹配空格,默认只匹配一个

\S

 匹配非空格,默认只匹配一个

\w

 匹配0-9  a-z  A-Z  _,默认只匹配一个

\W

匹配非0-9  a-z  A-Z  _之外的字符,默认只匹配一个

()

标记一个子表达式的开始和结束位置

[]

满足[]内任意一个匹配即可,最多只能匹配一个

?

 非贪婪匹配模式

通配符:.

>>> a = 'hello world'
>>> b = re.search('w.',a)
>>> b
<_sre.SRE_Match object; span=(6, 8), match='wo'>
>>> b.group()
'wo'

通配符:*和?

>>> a = 'hello world'
>>> b = re.search('w.*',a)
>>> b
<_sre.SRE_Match object; span=(6, 11), match='world'>
>>> b.group()
'world'
>>> c = re.search('w.*?',a)
>>> c
<_sre.SRE_Match object; span=(6, 7), match='w'>

通配符:+和?

>>> a = 'hello world'
>>> b = re.search('w.+',a)
>>> b
<_sre.SRE_Match object; span=(6, 11), match='world'>
>>> c = re.search('w.+?',a)
>>> c
<_sre.SRE_Match object; span=(6, 8), match='wo'>

通配符:\d和\D

>>> a = '123abc456'
>>> b = re.search('\d',a)
>>> b
<_sre.SRE_Match object; span=(0, 1), match='1'>
>>> c = re.search('\D',a)
>>> c
<_sre.SRE_Match object; span=(3, 4), match='a'>
>>> a = '123abc456'
>>> d = re.search('\D*',a)  # 这个结果我理解的应该是abc,不知道为什么没有匹配到,匹配前一个字符0次或者更多次,贪婪模式
>>> d   
<_sre.SRE_Match object; span=(0, 0), match=''>    
>>> d = re.search('\D',a)
>>> d
<_sre.SRE_Match object; span=(3, 4), match='a'>
>>> d = re.search('\D\D\D',a)
>>> d
<_sre.SRE_Match object; span=(3, 6), match='abc'>
>>> d = re.search('\D+',a)
>>> d
<_sre.SRE_Match object; span=(3, 6), match='abc'>

四、group使用

功能:分组

group()

返回匹配的整个表达式

group(i)

返回匹配的分组表达式

>>> a = 'helloworldmynameismarry'
>>> b = re.search('(.*)world(.*)',a)
>>> b.group()
'helloworldmynameismarry'
>>> b.group(1)
'hello'
>>> b.group(2)
'mynameismarry'

五、findall使用

findall 提取出来的就是列表对象,不需要使用group()

语法:re.findall(‘想匹配的字符表达式’, string)

a = 'http://www.baidu.com'
b = re.findall('\w',a)
print(b)   # ['h', 't', 't', 'p', 'w', 'w', 'w', 'b', 'a', 'i', 'd', 'u', 'c', 'o', 'm']
print(type(b)) # <class 'list'>

六、sub使用

功能:替换

语法:re.search(‘原string中要被替换的字符’, ‘新字符’,string)

a = 'http://www.baidu.com'
b = re.sub('w','c',a)   # 将w替换成c
print(b)   # http://ccc.baidu.com

猜你喜欢

转载自blog.csdn.net/loner_fang/article/details/83149166