zoukankan      html  css  js  c++  java
  • python正则表达式

    re.match()函数只检测RE是不是在string的开始位置匹配
    re.match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none

    # 语法
    # re.match(pattern, string, flags=0)
    # eg_v1 import re match = "https://www.python.org" print (re.match("http",match).span()) # span() 返回一个元组包含匹配 (开始,结束) 的位置 # (0, 4) print (re.match("www",match)) # None

      


    re.search函数会在字符串内查找模式匹配,直到找到第一个匹配然后返回,如果字符串没有匹配,则返回None

    # 语法
    # re.search(pattern, string, flags=0)
    
    # eg_v2
    import re
    
    print (re.search("https","https://www.baidu.com").span())
    # (0, 5)
    print (re.search("baidu","https://www.baidu.com").span())
    # (12, 17)



    re.sub函数,re.sub用于替换字符串中的匹配项
    # 语法:
    # re.sub(pattern, repl, string, count=0, flags=0)
    # 参数:
    # pattern : 正则中的模式字符串。
    # repl : 替换的字符串,也可为一个函数。
    # string : 要被查找替换的原始字符串。
    # count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
    
    # eg_v3
    import re
    txt = "A man is known by the silence he keeps"
    print (re.sub(r"s+","_",txt))
    # A_man_is_known_by_the_silence_he_keeps


    re.compile 函数,把正则表达式编译成一个正则表达式对象
    # 语法
    # re.compile(pattern, flags=0)
    
    # eg_v4
    import re
    tsxt = "Happiness is in the doing, right? Not in the getting what you want."
    regex = re.compile(r"w*dow*")
    print (regex.findall(tsxt))  #查找所有包含'do'的单词
    # ['doing']
    print (regex.sub(lambda m: "[" + m.group(0) + "]",tsxt))  #将字符串中含有'do'的单词用[]括起来
    # Happiness is in the [doing], right? Not in the getting what you want.
    

      

  • 相关阅读:
    [Nowcoder]2020牛客寒假算法基础集训营3
    [Nowcoder]2020牛客寒假算法基础集训营2
    [Nowcoder]2020牛客寒假算法基础集训营1
    [备份]算法模板大集锦
    [东西]neverOpen
    [随笔]ICPC2.0
    [知识点]C++中STL容器之set
    [知识点]数列分块入门1-9
    [知识点]C++中STL容器之vector
    [知识点] 1.3.1 STL简介
  • 原文地址:https://www.cnblogs.com/xieshengsen/p/6727078.html
Copyright © 2011-2022 走看看