Python 替换两个字符串之间的所有文本

Python 替换两个字符串之间的所有文本,python,Python,假设我有: 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''' 我需要一种方法来替换(或删除)并在“This”和“ok”之间添加文本,这样当我调用它时,a现在等于: a = "Example String" 我找不到任何似乎有效的通配符。非常感谢您的帮助。您需要: a=re.su

假设我有:

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'''
我需要一种方法来替换(或删除)并在“This”和“ok”之间添加文本,这样当我调用它时,a现在等于:

a = "Example String"
我找不到任何似乎有效的通配符。非常感谢您的帮助。

您需要:

a=re.sub('This.*ok','',a,flags=re.DOTALL)

如果你想知道第一句话和最后一句话:

re.sub(r'^\s*(\w+).*?(\w+)$', r'\1 \2', a, flags=re.DOTALL)

DOTALL标志是关键。通常,“.”字符与换行符不匹配,因此不能在字符串中跨行匹配。如果设置了DOTALL标志,re将根据需要在多行中匹配“.*”。

另一种方法是使用字符串拆分:

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

    return leadingText + delimeterA + replacementText + delimterB + trailingText
限制:

  • 不检查分隔符是否存在
  • 假定没有重复的分隔符
  • 假定分隔符的顺序正确

  • 使用
    re.sub
    :它将两个字符或符号或字符串之间的文本替换为所需的字符或符号或字符串

    format: re.sub('A?(.*?)B', P, Q, flags=re.DOTALL)
    
    让我们看一个以html代码作为输入的示例

    input_string = '''<body> <h1>Heading</h1> <p>Paragraph</p><b>bold text</b></body>'''
    

    对正在发生的事情进行详细的阐述会有更大的帮助。这是最好的答案!我能够搜索并找到这个答案的速度比我打字的速度快!这也正是我想要编写代码的方式。谢谢 where A : character or symbol or string B : character or symbol or string P : character or symbol or string which replaces the text between A and B Q : input string re.DOTALL : to match across all lines
    import re
    re.sub('\nThis?(.*?)ok', '', a,  flags=re.DOTALL)
    
    output : ' Example String'
    
    input_string = '''<body> <h1>Heading</h1> <p>Paragraph</p><b>bold text</b></body>'''
    
    re.sub('<p>?(.*?)</p>', '', input_string,  flags=re.DOTALL)
    
    output : '<body> <h1>Heading</h1> <b>bold text</b></body>'
    
    re.sub('<p>?(.*?)</p>', 'test', input_string,  flags=re.DOTALL)
    
    otput : '<body> <h1>Heading</h1> test<b>bold text</b></body>'