python正则表达式与re模块

python中的re模块常用函数/方法

0.正则表达式对象  (re.compile(patternflags=0)

将正则表达式编译成正则表达式对象,该对象可调用正则表达式对象方法如:re.match(),re.search(),re.findall等。

prog = re.compile(pattern)
result = prog.match(string)
//上下两种写法意义相同
result = re.match(pattern, string)

1.匹配对象及方法              (Match.group([group1...]),  Match.groups(),Match.groupdict())  (?P<name>

正则表达式对象成功调用match,search方法时返回的对象。主要有两个方法group()和groups()。(失败时返回None,而None调用这两个方法会出现异常)

group()函数通常用于普通方式显示所有的匹配部分,也可用序号检索各个匹配子组。

groups()函数用于获取一个包含所有匹配子字符串的元组。(在只有一个匹配子组时会返回空元组)

ob = re.compile(r'(w+)-(d+)')  #()将正则表达式分成了两个子组
m = re.match(ob,'abc-123')
m.group()          #完整匹配
'abc-123'    
m.group(1)         #匹配子组1
'abc'
m.group(2)         #匹配子组2
'123'
m.groups()
('abc', '123')     #全部子组

(?P<name>)特殊符号可以使用名称标识符来保存匹配而不是数字。此时使用groupdict()方法返回一个字典,key为所给的名称标识符,而value为保存的匹配。

ob = re.compile(r'(?P<first>w+)-(?P<second>d+)')
m = re.match(ob,'abc-123')
m.groupdict()
{'second': '123', 'first': 'abc'}

2.匹配字符串      (re.match(patternstringflags=0), re.search())

match()方法从字符串的起始部分对模式进行匹配,如果匹配成功,返回一个匹配对象,失败则返回None。

search()方法从任意位置对正则表达式对象搜索第一次出现的匹配,成功则返回一个匹配对象,失败返回None。

>>> m = re.search('tif','beautiful')        
>>> m.group()       
'tif'     #匹配成功
>>> m.groups()
()           #返回空元组    
>>> m = re.match('tif','beautiful')
>>> m.group()          #返回None,而None没有group()方法
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    m.group()
AttributeError: 'NoneType' object has no attribute 'group'

3.查找每一次出现的位置  (re.findall(patternstringflags=0))      re.finditer()

findall()查询字符串中某个正则表达式模式全部的非重复出现情况。与search()类似,而与之不同的是,findall()方法返回一个列表,如果匹配成功则列表包含所有成功的匹配部分;如果匹配失败则返回空列表。

finditer()与findall类似(包含所有成功匹配),但它返回一个迭代器

>>> s = 'This and that and the'
>>> re.findall(r'(thw+)',s,re.I)  //findall返回列表
[
'This', 'that', 'the']
>>> it = re.finditer(r'(thw+)',s,re.I)  //返回迭代器,用next()方法
>>> g = next(it)     >>> g.groups() ('This',)>>> g = next(it) >>> g.group(1) 'that' >>> g = next(it) >>> g.group(1) 'the' >>> [g.group(1) for g in re.finditer(r'(thw+)',s,re.I)]  //列表推导式 ['This', 'that', 'the']

4.搜索与替换   (re.sub(patternreplstringcount=0flags=0))      re.subn()

将某字符串中的所有匹配正则表达式的部分进行某种形式的替换。sub()与subn()几乎一样,sub()返回值是替换的个数,subn()返回值是元组 :(替换后的字符串,替换个数)。

>>> re.sub('hello','HELLO','hello the hello and world
')  //将所有hello替换为HELLO
'HELLO the HELLO and world
'  
>>> re.subn('hello','HELLO','hello the hello and world
')
('HELLO the HELLO and world
', 2)
>>> re.sub('hello','world','hello the hello and world
',1)  //替换一个hello,即添加count参数
'world the hello and world
'
>>> re.subn('[ed]','world','hello the hello and world
')  //将e或d替换为world,替换了5个
('hworldllo thworld hworldllo anworld worlworld
', 5)

5.分隔字符串  (re.split(patternstringmaxsplit=0flags=0))  //类似于字符串的split()用法

6.扩展符号  (前述方法的flags参数;而括号中为正则表达式的扩展符号,两种相同作用,用一种即可)

re.I/IGNORECASE    (?i)  不区分大小写的匹配
>>> re.findall(r'(?i)yes','yes Yes YES!!')    //(?i)不区分大小写,正则表达式层面
['yes', 'Yes', 'YES']
>>> re.findall(r'yes','yes Yes YES!!',re.I)  //re.I不区分大小写,python语言层面;下同
['yes', 'Yes', 'YES']
re.M/MULTILINE  (?m)   实现跨行搜索
>>> re.findall(r'(?im)(^th[w]+)',"""
This line is the first
another line
that line is the end""")
['This', 'that']
re.S/DOTALL  (?s)        使  .  符号能表示 符号
re.X/VERBOSE      (?x)        通过抑制在正则表达式中使用空白符来创建更易读的正则表达式
>>> re.search(r'''(?x)
((d{3}))  //区号
[ ]  //空格
(d{3})  //前缀
-  //横线
(d{4})  //末尾数字
''','(800) 555-1212').groups()
('800', '555', '1212')

(?:...)可以对正则表达式分组,但不保存该分组用于后续检索或应用。

>>> re.findall(r'(?:w+.)*(w+.com)','baidu.com www.baidu.com code.baidu.com')  //不保存(w+.)*匹配的分组,因而www,code均不出现在结果中
['baidu.com', 'baidu.com', 'baidu.com']

(?=...)(?!...)可以实现前视匹配。前者正向前视断言,后者负向前视断言。通俗来说:(?=...)仅仅获取...表达式前的字符串,忽略该表达式;(?!...)则获取后面的字符串。

import re
result = re.findall(r'w+(?= van Rossum)',
"""
    guido van Rossum
    tim peter
    Alex Martelli
    Just van Rossum
    Raymond Hettinger
""")
print(result)

['guido', 'Just']    //结果,忽略van Rossum而只保存该字符串前面的部分

正则表达式对象的另一种调用方法

Pattern.match(string[, pos[, endpos]])

Pattern.search(string[,pos[,endpos]])

Pattern.findall(string[, pos[, endpos]])

Pattern.finditer(string[, pos[, endpos]])

区别在于可调整pos,endpos参数来调整匹配范围

import re
ob = re.compile('llo')
m1 = ob.match('hello world')
m2 = ob.match('hello world', 2)
print(m1, m2.group())
None llo            //match从头匹配,m1为空;从第三个开始匹配,则m2匹配成功

对正则表达式特殊符号无了解可访问: 正则表达式常用字符及符号

原文地址:https://www.cnblogs.com/lht-record/p/10223030.html