zoukankan      html  css  js  c++  java
  • python-re模块(compile,findall:查找结果是列表,sub:替换所有符合条件的元素,serach:查找结果是一个元素 #字符串以空格为分割元素)


    # ①:单独使用findall
    import re
    v3 = re.findall(r"html$", "https://docs.python.org/3/whatsnew/3.6.html")
    v2 = re.findall(r"^http", "https://docs.python.org/3/whatsnew/3.6.html")
    v1 = re.findall(r"python", "https://docs.python.org/3/whatsnew/3.6.html")
    print('v3:结尾', v3)
    print('v2:开头', v2)
    print('v1:包含', v1)
    """
    v3:结尾 ['html']
    v2:开头 ['http']
    v1:包含 ['python']
    """
    #------------------------------------------
    # ②:compile搭配findall使用
    import re
    #在content内容中,找到包含m的单词
    content = 'Hello, I am Jerry, from jiangsu, a montain city, nice to meet you'
    com = re.compile('w*mw*').findall(content)
    print(com)
    # ['am', 'from', 'montain', 'meet']
    #------------------------------------------
    #③:单独使用sub
    import re
    # sub第一种用法,三个参数,第一参数需要替换的数,第二个参数替换之后的参数,第三个参数是文本值
    a = re.sub(r'(d+)', 'hi', 'my numer is 800 and your num is 600')
    print(a)
    #my numer is hi and your num is hi
    #-----------------------
    #④:sub结合compile使用
    s = "hello 1234, goodbye, 235"
    print('s:文本值', s)
    # pat需要替换的内容
    pat = r'd+'
    m = re.compile(pat).sub('666', s)
    print('m:数字替换666', m)
    # s:文本值 hello 1234, goodbye, 235
    # m:数字替换666 hello 666, goodbye, 666
    #------------------------------
    #⑤:search单独使用
    import re
    a = re.search('d+','2a3 1422sadf')
    print(a)
    #
    # <re.Match object; span=(0, 1), match='2'>
    #----------------------------------------
    #⑥:search结合compile使用
    content = 'Hello, I am Jerry, from jiangsu, a montain city, nice to meet you'
    ret = re.compile('w*ow*').search(content)
    print(ret.group())
    print(ret)
    # Hello
    # <re.Match object; span=(0, 5), match='Hello'>
  • 相关阅读:
    React项目搭建与部署
    桌面应用之electron开发与转换
    React Native之支付集成(微信 支付宝)(ios android)
    WEB通知和React Native之即时通讯(iOS Android)
    React Native之配置URL Scheme(iOS Android)
    Mybatis操作oracle数据库的一些坑
    java -jar和hadoop jar的区别
    springBoot启动的时候动态选择装载某些bean
    Java常用正则表达式
    java获取当前运行的方法名称
  • 原文地址:https://www.cnblogs.com/12260420zxx/p/13663267.html
Copyright © 2011-2022 走看看