search

Home  >  Q&A  >  body text

正则表达式 - Python re.sub() 的一个奇怪问题?

大家讲道理大家讲道理2912 days ago542

reply all(4)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 10:01:51

    When

    matches the second bracket, the value is mo.group(2)

    mo.group(1) 没匹配到就 None Got it

    def mark(mo):
        # print(mo.group(1))
        for i in range(1, 4):
            match_result = mo.group(i)
            if match_result is not None:
                print(i)
                return match_result
    
    
    re_sub = re.sub(r'@(yangxg)|@(zengshao)|@(zmrenwu)', mark, '@yangxg @zengshao @zmrenwu')
    print(re_sub)
    

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:01:51

    Maybe it’s better to write like this? The output meets your requirements

    def mark(mo):
        print(mo.group(1))
        return mo.group(1)[1:]
    
    data = re.sub(r'(@\w+)', mark, '@yangxg @zengshao @zmrenwu')
    print data

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:01:51

    import re
    data = re.sub(r'@(\w+)', '\\1','@yangxg @zengshao @zmrenwu')
    print data
    

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:01:51

    result = re.sub(r'@(\w+)', lambda mo: mo.group(1), '@yangxg @zengshao @zmrenwu')

    reply
    0
  • Cancelreply