Use Python Match object in string with backreferences

前端 未结 1 767
南方客
南方客 2021-01-24 21:47

Does Python have a capability to use a Match object as input to a string with backreferences, eg:

match = re.match(\"ab(.*)\", \"abcd\")
print re.some_replace_fu         


        
相关标签:
1条回答
  • 2021-01-24 22:08

    You can use re.sub (instead of re.match) to search and replace strings.

    To use back-references, the best practices is to use raw strings, e.g.: r"\1", or double-escaped string, e.g. "\\1":

    import re
    
    result = re.sub(r"ab(.*)", r"match is: \1", "abcd")
    print(result)
    # -> match is: cd
    

    But, if you already have a Match Object , you can use the expand() method:

    mo = re.match(r"ab(.*)", "abcd")
    result = mo.expand(r"match is: \1")
    print(result)
    # -> match is: cd
    
    0 讨论(0)
提交回复
热议问题