我正在寻找删除包含多行字符串中特定字符串的行之前的每一行的方法,如下所示:
string1
string2
string3
==== bump
string4
string5
string6
==== bump
但只有第一个匹配一个......
最后,我希望将其作为输出:
==== bump
string4
string5
string6
==== bump
import re
text = '''\
string1
string2
string3
==== bump
string4
string5
string6
==== bump'''
print(re.split(r'(=== bump)', text, maxsplit=1)[-1])
产量
string4
string5
string6
==== bump
import io
import itertools
import sys
lines = io.StringIO(u'''\
string1
string2
string3
==== bump
string4
string5
string6
==== bump
''')
sep = '==== bump'
it = itertools.dropwhile(lambda line: not line.startswith(sep), lines)
sys.stdout.writelines(it)
输出
==== bump
string4
string5
string6
==== bump
假设您已将文本存储在/tmp/corpus中,您可以使用以下 Perl 单行代码:
perl -ne 'print if /\A==== bump/ ... /\A==== bump/' /tmp/corpus
这利用了 Perl范围运算符的强大功能。如果要在 Python 程序中捕获 Perl 的输出,可以使用Python 子进程模块。例如:
import subprocess
result = subprocess.check_output(
"perl -ne 'print if /\A==== bump/ ... /\A==== bump/' /tmp/corpus",
shell=True)
print result
lines = '''
string1
string2
string3
==== bump
string4
string5
string6
==== bump
'''
import re
sep = '==== bump'
matched = re.search('{0}.*?{0}'.format(re.escape(sep)), lines, flags=re.S)
print(matched.group(0))