zoukankan      html  css  js  c++  java
  • python正则re

    import re
    line = "Catsaresmarterthandogs"
    matchObj = re.match( r'(.*)are(w{2})(.*)', line, re.M|re.I)
    if matchObj:
    print ("matchObj.group() : ", matchObj.group())#group返回匹配的整个字符串,groups返回匹配各分组的元祖
    print ("matchObj.group(1) : ", matchObj.group(1))#span(1)返回匹配第一个分组的起始索引
    print ("matchObj.group(2) : ", matchObj.group(2))
    print ("matchObj.group(2) : ", matchObj.group(3))
    else:
    print ("No match!!")

    matchObj.group() : Catsaresmarterthandogs
    matchObj.group(1) : Cats
    matchObj.group(2) : sm
    matchObj.group(2) : arterthandogs

    search用法一样
    ————————————————————————————————————————————————————————————————————————————
    re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
    而re.search匹配整个字符串,直到找到一个匹配。match 和 search 是匹配一次 findall 匹配所有
    num = re.sub(r'#.*$', "", str) re.sub(替换规则,替换成xx,操作的字符串);用于替换字符串中的匹配项

    ——————————————————————————————————————————————————————————————
    # 将匹配的数字乘以 2
    import re
    # 将匹配的数字乘以 2
    def double(matched):
    value = int(matched.group('value'))
    return str(value * 2)
    s = 'A23G4HFD567'
    print(re.sub('(?P<value>d+)', double, s))#A46G8HFD1134
    ——————————————————————————————————————————————————————————————————
    re.finditer(r"d+","12a32bc43jf3") 返回匹配结果为一个迭代器
    re.split('W+', 'w3cschool, w3cschool, w3cschool.')分割匹配结果为一个列表
    ————————————————————————————————————
    [^...] [^abc] 匹配除了a,b,c之外的字符[^0-9] 匹配除了数字外的字符


  • 相关阅读:
    Spring cloud学习总结
    Spring boot学习笔记
    Rabbitmq安装步骤
    Mongodb 笔记采坑
    Rabbit Docker 部署及采坑
    各种知识汇总
    Echart 随便写的
    Linux常用命令
    Redis学习笔记
    Docker使用总结
  • 原文地址:https://www.cnblogs.com/qinyios/p/10016706.html
Copyright © 2011-2022 走看看