首页 > 编程语言 >python正则表达式记录

python正则表达式记录

时间:2023-03-31 17:46:13浏览次数:37  
标签:do string 记录 python pattern two hand 正则表达式 repl

今天写个脚本用到正则表达式,查阅了资料加问了gpt老师终于解决,在此记录。

记录两种正则表达式有用的用法:

1、匹配指定了前后文的字符串

如我们需要匹配'on the one hand'中的'one',而不要'on the other hand'中的'other';需要用到正则表达式语法中的“特殊构造”:(?...),之所以是特殊构造因为这个(?...)不会像正常括号算在分组中,而只作为匹配要求。

 

import re

text = "On the one hand, we have the option to do X. On the other hand, we have the option to do Y."
pattern = "(?<=in the )one(?= hand)"

matches = re.findall(pattern, text)
print(matches) # ['one']

 

2、有大量文本需要替换,且具有替换规则

如现在

text = "On the one hand, ... On the two hand, ...On the other hand, ..."

我们要把'one'改成'1','two'改成2,则可以用如下较优雅的写法

import re

project = {
        'one': '1',
        'two': '2'
    }

text = "On the one hand, we have the option to do X. On the two hand, we have the option to do Y.On the other hand, we have the option to do Z."
pattern = "(?<=in the )" + '|'.join(project.keys()) + "(?= hand)"

res = re.sub(ptn,
               lambda match: project[match],
               text)
print(res)
# "On the 1 hand, we have the option to do X. On the 2 hand, we have the option to do Y.On the other hand, we have the option to do Z."

注意此处用到了re.sub(pattern, repl, string, count=0, flags=0)

需要注意的点是参数repl可以是字符串,也可以是一个函数,若为字符串很好理解;若是函数则输入的参数为match,是pattern匹配了string后的结果。所以上面用lambda match: project[match]返回匹配了'one','two'映射后的字符串

def sub(pattern, repl, string, count=0, flags=0):
    """Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the Match object and must return
    a replacement string to be used."""
    return _compile(pattern, flags).sub(repl, string, count)

正则匹配的规则还是挺多挺复杂的,想要得心应手也不是非常简单,还是多动手吧。

标签:do,string,记录,python,pattern,two,hand,正则表达式,repl
From: https://www.cnblogs.com/llllrj/p/17276998.html

相关文章

  • 记录使用mybatis时踩到的坑-integer类型数据为0时,会判断为:等于空字符串为true
    因为做查询操作时,需要设置为传入参数值才进行查询,于是判断条件是:status!=nullandstatus!=''即mapper层的写法:<iftest="status!=nullandstatus!=''">andstatus=#{status}</if> 但设计表时,默认status=0表示正常状态,status=1表示其他状态。当传入status=0进......
  • 跟着查老四学Python Day 4:列表推导式 生成器 迭代器
    忽略掉例行寒暄,让查老四直接讲课了列表推导式(ListComprehension)列表推导式是一种简洁的构建列表的方法。它可以将一个循环和条件表达式结合起来,从而生成一个新的列表。示例:#普通循环创建一个列表squares=[]forxinrange(1,6):squares.append(x**2)print(squares)......
  • QMainWindow知识点记录
    1.新建action toolbaropenFileAction = new QAction(QIcon(":/pic/open"), QString::fromLocal8Bit("打开"), this); openFileAction->setShortcut(tr("Ctrl+O")); openFileAction->setStatusTip(tr("打开一个文件"));-------......
  • MS SQL Server SQL刷题记录
    MSSQLServerSQL方言和mysqlsql略有不同目录保留4位小数求曼哈顿距离和欧几里得距离求中位数表联结表联结,我真心建议给你的列命名的时候不要瞎命名保留4位小数SELECTCAST(ROUND(SUM(LAT_N),4)ASDECIMAL(10,4))FROMSTATIONWHERELAT_N>38.7880ANDLAT_N<137.23......
  • Python 数字类型之 int float
    数字常量int:一般的整数,long:长整型,2.x版本需在数字后加“L”或“l”,表示长整型如100000000L;python3.x版本后不分长整型,统一为int,不可加“L”或“l”float:浮点数,1.0也为浮点数,float可强制转换为int,取整;print(type(1234))print(type(-24))print......
  • 关于python 的if __name__ == "__main__"的模块测试
    if__name__=="__main__"也就是说执行当前文件,不调用模块的时候__name__=__main__调用模块的时候,测试如下:1、新建test01.py文件测试代码如下print("这条消息来自test01")deffunc():print('hello,world!***')print("这条消息来自func")if__name__=="__......
  • python isinstance()函数
    pythonisinstance()函数描述isinstance()函数来判断一个对象是否是一个已知的类型,类似type()isinstance()与type()的区别type()不会认为子类是一种父类类型,不考虑继承关系isinstance()会认为子类是一种父类类型,考虑继承关系如果要判断两个类型是否相同推荐使用isinstanc......
  • Python3内置函数之C系列
    1、callable()callable()是一个内置函数,用于检查给定对象是否是可调用的。如果对象是可调用的,则返回True,否则返回False。可调用对象包括函数、方法、类和某些类的实例。如果一个对象定义了__call__()方法,则也被认为是可调用的。 2、chr()chr()是Python内置函数之一,用于......
  • 【python基础】python字典根据值查询键
    前言 测试>>>tfl_label={'circle_green':0,'circle_red':1,'circle_yellow':2,'left_green':3,'left_red':4,'left_yellow':5,'nomotor_green':6,'nomotor_red':7,......
  • ubuntu16.04升级python3.7.1教程
    ubuntu16.04升级python3.7.1教程准备sudoapt-getinstall--reinstallzlibczlib1gzlib1g-devsudoapt-getinstalllibffi-devlibssl-devlibreadline-dev-y安装使用python官方站点的以下命令下载Python。您也可以下载最新版本代替下面指定的版本#下载python3......