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] 匹配除了数字外的字符


  • 相关阅读:
    [BZOJ2296] [POJ Challenge] 随机种子
    [BZOJ1026] [SCOI2009] windy数 (数位dp)
    [BZOJ1306] [CQOI2009] match循环赛 (搜索)
    [BZOJ2654] tree (kruskal & 二分答案)
    [BZOJ3506] [Cqoi2014] 排序机械臂 (splay)
    [BZOJ1552] [Cerc2007] robotic sort (splay)
    [BZOJ3110] [Zjoi2013] K大数查询 (树套树)
    BZOJ3611: [Heoi2014]大工程
    BZOJ2286: [Sdoi2011]消耗战
    BZOJ3876: [Ahoi2014]支线剧情
  • 原文地址:https://www.cnblogs.com/qinyios/p/10016706.html
Copyright © 2011-2022 走看看