让我们说:
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'''
Run Code Online (Sandbox Code Playgroud)
我需要一种方法在"This"和"ok"之间进行替换(或者只是删除)和文本,这样当我调用它时,现在等于:
a = "Example String"
Run Code Online (Sandbox Code Playgroud)
我找不到任何似乎有效的通配符.任何帮助深表感谢.
Kab*_*bie 13
>>> import re
>>> re.sub('\nThis.*?ok','',a, flags=re.DOTALL)
' Example String'
Run Code Online (Sandbox Code Playgroud)
Zac*_*ann 10
另一种方法是使用字符串分割:
def replaceTextBetween(originalText, delimeterA, delimterB, replacementText):
leadingText = originalText.split(delimeterA)[0]
trailingText = originalText.split(delimterB)[1]
return leadingText + delimeterA + replacementText + delimterB + trailingText
Run Code Online (Sandbox Code Playgroud)
限制:
用途:用所需的字符或符号或字符串替换两个字符或符号或字符串re.sub
之间的文本。
format: re.sub('A?(.*?)B', P, Q, flags=re.DOTALL)
Run Code Online (Sandbox Code Playgroud)
在哪里 A : 字符或符号或字符串 B:字符或符号或字符串 P:替换A和B之间文本的字符或符号或字符串 问:输入字符串 re.DOTALL :匹配所有行
import re
re.sub('\nThis?(.*?)ok', '', a, flags=re.DOTALL)
output : ' Example String'
Run Code Online (Sandbox Code Playgroud)
让我们看一个以 html 代码作为输入的示例
input_string = '''<body> <h1>Heading</h1> <p>Paragraph</p><b>bold text</b></body>'''
Run Code Online (Sandbox Code Playgroud)
目标:删除<p>
标签
re.sub('<p>?(.*?)</p>', '', input_string, flags=re.DOTALL)
output : '<body> <h1>Heading</h1> <b>bold text</b></body>'
Run Code Online (Sandbox Code Playgroud)
目标:<p>
用单词替换标签:test
re.sub('<p>?(.*?)</p>', 'test', input_string, flags=re.DOTALL)
otput : '<body> <h1>Heading</h1> test<b>bold text</b></body>'
Run Code Online (Sandbox Code Playgroud)