Python Regex, re.sub, replacing multiple parts of pattern?

前端 未结 3 1949
情深已故
情深已故 2021-02-07 05:55

I can\'t seem to find a good resource on this.. I am trying to do a simple re.place

I want to replace the part where its (.*?), but can\'t figure out the syntax on how t

相关标签:
3条回答
  • 2021-02-07 06:20
    >>> import re
    >>> originalstring = 'fksf var:asfkj;'
    >>> pattern = '.*?var:(.*?);'
    >>> pattern_obj = re.compile(pattern, re.MULTILINE)
    >>> replacement_string="\\1" + 'test'
    >>> pattern_obj.sub(replacement_string, originalstring)
    'asfkjtest'
    

    Edit: The Python Docs can be pretty useful reference.

    0 讨论(0)
  • 2021-02-07 06:30

    The python docs are online, and the one for the re module is here. http://docs.python.org/library/re.html

    To answer your question though, Python uses \1 rather than $1 to refer to matched groups.

    0 讨论(0)
  • 2021-02-07 06:32
    >>> import re
    >>> regex = re.compile(r".*?var:(.*?);")
    >>> regex.sub(r"\1test", "fksf var:asfkj;")
    'asfkjtest'
    
    0 讨论(0)
提交回复
热议问题