python中正则表达式的使用方法

yipeiwu_com6年前Python基础

本文主要关于python的正则表达式的符号与方法。

findall: 找寻所有匹配,返回所有组合的列表
search: 找寻第一个匹配并返回
sub: 替换符合规律的内容,并返回替换后的内容
.:匹配除了换行符以外的任意字符

a = 'xy123'
b = re.findall('x...',a)
print(b)
# ['xy12']

*:匹配前一个字符0次或者无限次

a = 'xyxy123'
b = re.findall('x*',a)
print(b)
# ['x', '', 'x', '', '', '', '', '']

?:匹配前一个字符0次或者1次

a = 'xy123'
b = re.findall('x?',a)
print(b)
# ['x', '', '', '', '', '']

.*:贪心算法

b = re.findall('xx.*xx',secret_code)
print(b)
# ['xxIxxfasdjifja134xxlovexx23345sdfxxyouxx']

.*?:非贪心算法

c = re.findall('xx.*?xx',secret_code)
print(c)
# ['xxIxx', 'xxlovexx', 'xxyouxx']

():括号内结果返回

d = re.findall('xx(.*?)xx',secret_code)
print(d)
for each in d:
  print(each)
# ['I', 'love', 'you']
# I
# love
# you

re.S使得.的作用域包括换行符”\n”

s = '''sdfxxhello
xxfsdfxxworldxxasdf'''

d = re.findall('xx(.*?)xx',s,re.S)
print(d)
# ['hello\n', 'world']

对比findall与search的区别

s2 = 'asdfxxIxx123xxlovexxdfd'
f = re.search('xx(.*?)xx123xx(.*?)xx',s2).group(2)
print(f)
f2 = re.findall('xx(.*?)xx123xx(.*?)xx',s2)
print(f2[0][1])
# love
# love

虽然两者结果相同,但是search是搭配group来得到第二个匹配,而findall的结果是[(‘I', ‘love')],包含元组的列表,所以需要f2[0][1]来引入。

sub的使用

s = '123rrrrr123'
output = re.sub('123(.*?)123','123%d123'%789,s)
print(output)
# 123789123

例如我们需要将文档中的所有的png图片改变路径,即需要找到所有的 .png 结尾,再将其都加上路径,

import re

def multiply(m):
  # Convert group 0 to an integer.
  v = m.group(0)
  print(v)
  # Multiply integer by 2.
  # ... Convert back into string and return it.
  print('basic/'+v)
  return 'basic/'+v

结果如下

>>>autoencoder.png
  basic/autoencoder.png
  RNN.png
  basic/RNN.png
  rnn_step_forward.png
  basic/rnn_step_forward.png
  rnns.png
  basic/rnns.png
  rnn_cell_backprop.png
  basic/rnn_cell_backprop.png
  LSTM.png
  basic/LSTM.png
  LSTM_rnn.png
  basic/LSTM_rnn.png
  attn_mechanism.png
  basic/attn_mechanism.png
  attn_model.png
  basic/attn_model.png

仿照上面案例,我们可以方便的对我们的任务进行定制。

subn相比sub,subn返回元组,第二个元素表示替换发生的次数:

import re

def add(m):
  # Convert.
  v = int(m.group(0))
  # Add 2.
  return str(v + 1)

# Call re.subn.
result = re.subn("\d+", add, "1 2 3 4 5")

print("Result string:", result[0])
print("Number of substitutions:", result[1])
>>>
Result string: 11 21 31 41 51
Number of substitutions: 5

相关文章

50行Python代码实现人脸检测功能

50行Python代码实现人脸检测功能

  现在的人脸识别技术已经得到了非常广泛的应用,支付领域、身份验证、美颜相机里都有它的应用。用iPhone的同学们应该对下面的功能比较熟悉   iPhone的照片中有...

Python实现基于C/S架构的聊天室功能详解

Python实现基于C/S架构的聊天室功能详解

本文实例讲述了Python实现基于C/S架构的聊天室功能。分享给大家供大家参考,具体如下: 一、课程介绍 1.简介 本次项目课是实现简单聊天室程序的服务器端和客户端。 2.知识点 服务器...

Python pickle模块实现对象序列化

这篇文章主要介绍了Python pickle模块实现对象序列化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 作用 对Python对...

python 按照固定长度分割字符串的方法小结

有如下的一堆mac地址,需要更改成一定格式,如mac='902B345FB021'改为mac='90-2B-34-5F-B0-21'。 借助python脚本,可以轻松实现,原理就是:字符...

python使用Plotly绘图工具绘制散点图、线形图

python使用Plotly绘图工具绘制散点图、线形图

今天在研究Plotly绘制散点图的方法,供大家参考,具体内容如下 使用Python3.6 + Plotly Plotly版本2.0.0 在开始之前先说说,还需要安装库Numpy,安装方法...