python正则表达式与re模块

转载自:
https://www.cnblogs.com/lht-record/p/10223030.html
https://www.cnblogs.com/tsql/p/6381367.html

有修改

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

1.正则表达式对象  (re.compile(pattern, flags=0))

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

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

2.匹配对象及方法 (Match.group([group1, …]), Match.groups(),Match.groupdict()) (?P)

正则表达式对象成功调用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'}

3.匹配字符串 (re.match(pattern, string, flags=0), re.search())

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

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

#PythonConsole中运行
>>> 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'

4.查找每一次出现的位置 (re.findall(pattern, string, flags=0)) re.finditer()

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

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

>>> s = 'This and that and the'
>>> re.findall(r'(th\w+)',s,re.I)  //findall返回列表['This', 'that', 'the']>>> it = re.finditer(r'(th\w+)',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'(th\w+)',s,re.I)]  //列表推导式
['This', 'that', 'the']

5.搜索与替换 (re.sub(pattern, repl, string, count=0, flags=0)) re.subn()

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

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

6.分隔字符串 (re.split(pattern, string, maxsplit=0, flags=0))  //类似于字符串的split()用法

拓展

正则前面的 (?i) (?s) (?m) (?is) (?im)

(?i) 表示所在位置右侧的表达式开启忽略大小写模式

(?s) 表示所在位置右侧的表达式开启单行模式

(?m) 表示所在位置右侧的表示式开启指定多行模式

(?is) 更改句点字符 (.) 的含义,以使它与每个字符(而不是除 \n 之外的所有字符)匹配

(?im) 更改 ^ 和 $ 的含义,以使它们分别与任何行的开头和结尾匹配,而不只是与整个字符串的开头和结尾匹配

注意:(?s)通常在匹配有换行的文本时使用

注意:(?m)只有在正则表达式中涉及到多行的“^”和“$”的匹配时,才使用Multiline模式,上面的匹配模式可以组合使用,比如(?is),(?im)

另外,还可以用(?i:exp)或者(?i)exp(?-i)来指定匹配的有效范围

具体实例看下文

7.扩展符号  (前述方法的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) 使 . 符号能表示\n符号
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://blog.csdn.net/weixin_43407319/article/details/113390499

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值