Replace all text between 2 strings python

前端 未结 5 1415
再見小時候
再見小時候 2020-11-27 22:18

Lets say I have:

a = r\'\'\' Example
This is a very annoying string
that takes up multiple lines
and h@s a// kind{s} of stupid symbols in it
ok String\'\'\'
         


        
相关标签:
5条回答
  • 2020-11-27 22:42

    The DOTALL flag is the key. Ordinarily, the '.' character doesn't match newlines, so you don't match across lines in a string. If you set the DOTALL flag, re will match '.*' across as many lines as it needs to.

    0 讨论(0)
  • 2020-11-27 22:42

    Another method is to use string splits:

    def replaceTextBetween(originalText, delimeterA, delimterB, replacementText):
        leadingText = originalText.split(delimeterA)[0]
        trailingText = originalText.split(delimterB)[1]
    
        return leadingText + delimeterA + replacementText + delimterB + trailingText
    

    Limitations:

    • Does not check if the delimiters exist
    • Assumes that there are no duplicate delimiters
    • Assumes that delimiters are in correct order
    0 讨论(0)
  • 2020-11-27 22:46
    a=re.sub('This.*ok','',a,flags=re.DOTALL)
    
    0 讨论(0)
  • 2020-11-27 22:52

    If you want first and last words:

    re.sub(r'^\s*(\w+).*?(\w+)$', r'\1 \2', a, flags=re.DOTALL)
    
    0 讨论(0)
  • 2020-11-27 23:02

    You need Regular Expression:

    >>> import re
    >>> re.sub('\nThis.*?ok','',a, flags=re.DOTALL)
    ' Example String'
    
    0 讨论(0)
提交回复
热议问题