zoukankan      html  css  js  c++  java
  • Py中re.sub学习【转载】

    转自:https://www.crifan.com/python_re_sub_detailed_introduction/

    //这个网址讲的不错。

    1.re.sub的功能

    re是regular expression的缩写,表示正则表达式

    sub是substitute的缩写,表示替换;

    re.sub是个正则表达式方面的函数,用来实现通过正则表达式,实现比普通字符串的replace更加强大的替换功能;

    inputStr = "hello 111 world 111"
    replacedStr = inputStr.replace("111", "222")
    //这样可以进行替换
    inputStr = "hello 123 world 456"
    replacedStr = re.sub("d+", "222", inputStr)
    //这样可以把数字都换为222

     对于输入的一个字符串,利用正则表达式(的强大的字符串处理功能),去实现(相对复杂的)字符串替换处理,然后返回被替换后的字符串.

    2.re.sub的各个参数的详细解释

    re.sub共有五个参数。

    其中三个必选参数:patternreplstring

    两个可选参数:countflags

    2020-3-9————————————————

    看自己以前写的博客,真是辣鸡。。。学的真是太不认真了。

    1.小例子

    import re
    text="a
    cfoda!!"
    text=re.sub(r"[^a-zA-Z0-9]"," ",text)
    print(text)
    
    #输出:
    a cfoda  

    可以发现,它会将换行符 去掉,而且标点符号英文/中文都去掉了。

    2.总体学习

    https://github.com/ziishaned/learn-regex/blob/master/translations/README-cn.md

    可以发现这个讲的非常详细!善用知乎。。。

    https://www.runoob.com/python/python-reg-expressions.html

    这个也讲的很全面。

    import re
    text="The car parked in the garage."
    text=re.findall(r".ar",text)
    print(text)
    
    #输出:
    ['car', 'par', 'gar']

    是找到所有的。

    import re
    text="The car parked in the garage."
    text=re.sub(r".ar","233",text)
    print(text)
    
    #输出:
    The 233 233ked in the 233age.

    sub是替换,学会了正则语法的规则和这两个函数基本就可了。

    但是有一点奇怪,是不用在{}前吗?。。。

    import re
    text="The {car} parked in the garage."
    text=re.sub(r"{}","233",text)
    print(text)
    #输出:
    The {car} parked in the garage.
    
    
    text=re.sub(r"{","233",text)
    #输出:
    The 233car} parked in the garage.
    #这个倒是可以匹配上的
  • 相关阅读:
    防止重复点击
    刷新当前页面的几种方法
    PHP删除数组中空值
    json转化数组
    两个不能同时共存的条件orWhere查询
    SQLSTATE[42000]
    laravel一个页面两个表格分页处理
    Hash::make与Hash::check
    unbind()清除指定元素绑定效果
    二级联动
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/10648404.html
Copyright © 2011-2022 走看看