Regex in python: is it possible to get the match, replacement, and final string?

前端 未结 2 518
再見小時候
再見小時候 2020-12-29 03:39

For doing a regex substitution, there are three things that you give it:

  • The match pattern
  • The replacement pattern
  • The original string
  • <
2条回答
  •  执笔经年
    2020-12-29 04:03

    I looked at the documentation and it seems like you can pass a function reference into the re.sub:

    import re
    
    def re_sub_verbose(pattern, replace, string):
      def substitute(match):
        print 'Matched:', match.group(0)
        print 'Replacing with:', match.expand(replace)
    
        return match.expand(replace)
    
      result = re.sub(pattern, substitute, string)
      print 'Final string:', result
    
      return result
    

    And I get this output when running re_sub_verbose("(orig.*?l)", "not the \\1", "This is the original string."):

    Matched: original
    Replacing with: not the original
    This is the not the original string.
    

提交回复
热议问题