zoukankan      html  css  js  c++  java
  • re正则匹配替换字符串(sub和subn)

    前言

    python 里面可以用 replace 实现简单的替换字符串操作,如果要实现复杂一点的替换字符串操作,需用到正则表达式。
    re.sub用于替换字符串中匹配项,返回一个替换后的字符串,subn方法与sub()相同, 但返回一个元组, 其中包含新字符串和替换次数。

    sub介绍

    Python 的 re 模块提供了re.sub用于替换字符串中的匹配项,sub是substitute表示替换。

    使用语法

    sub(pattern, repl, string, count=0, flags=0)
    • pattern:该参数表示正则中的模式字符串;
    • repl:repl可以是字符串,也可以是可调用的函数对象;如果是字符串,则处理其中的反斜杠转义。如果它是可调用的函数对象,则传递match对象,并且必须返回要使用的替换字符串
    • string:该参数表示要被处理(查找替换)的原始字符串;
    • count:可选参数,表示是要替换的最大次数,而且必须是非负整数,该参数默认为0,即所有的匹配都会被替换;
    • flags:可选参数,表示编译时用的匹配模式(如忽略大小写、多行模式等),数字形式,默认为0。

    sub示例-repl传字符串

    将字符串中的hello替换成数字123

    import re
    
    #替换s中的hello为123,
    s = "hello,world!!!"
    print(re.sub(r'hello', "123", s))
    #123,world!!!

    把字符串中的连续数字替换成hello

    import re
    # 把字符串中的连续数字替换成hello
    s = "the number 0746-8798098"
    print(re.sub(r'd+', "hello", s))
    # the number hello-hello

    替换时间格式 01/11/2021 替换成 2021/01/11

    import re
    
    # 替换时间格式 01/11/2021 替换成 2021/01/11
    
    s = "today is 09-12-2021"
    day = re.sub(r'(d{2})-(d{2})-(d{4})', r'3-2-1', s)
    print(day) # today is 2021-12-09
    
    # 也可以用g<3>-g<2>-g<1>
    day2 = re.sub(r'(d{2})-(d{2})-(d{4})', r'g<3>-g<2>-g<1>', s)
    print(day) # today is 2021-12-09

    3 和 g<3>指代的的都是前面匹配的第3个分组

    repl传函数对象

    import re
    
    def fun(m):
        return m.group(1).title()+' '+m.group(2).title()  #首字符大写
    
    str1='hello world ~~~~~~~~~'
    
    str1=re.sub(r"(w+) (w+)",fun,str1)
    print(str1)
    # Hello World ~~~~~~~~~

    count替换次数

    sub 加 count 参数可以控制要替换的次数,而且必须是非负整数,该参数默认为0,表示所有的匹配都会被替换;

    import re
    
    # 替换字符串中的空格为123,只替换一次
    s = "We are happy"
    print(re.sub(" ", "123", s, count=1))
    # We123are happy

    subn方法使用

    subn方法与sub()相同, 但返回一个元组, 其中包含新字符串和替换次数。

    # 替换字符串中的空格为123
    s = "We are happy"
    print(re.subn(" ", "123", s)) 
    #('We123are123happy', 2)
  • 相关阅读:
    前端进击的巨人(一):执行上下文与执行栈,变量对象
    读书笔记(06)
    前端博客收藏
    Nodejs-Can't set headers after they are sent
    Mac OS安装包管理工具Homebrew教程
    webpack自动化构建脚本指令npm run dev/build
    使用express搭建node中间件
    【转】基于localStorage的资源离线和更新技术
    web前端性能优化
    Vue生命周期详解
  • 原文地址:https://www.cnblogs.com/lvhuayan/p/15260375.html
Copyright © 2011-2022 走看看