1

我正在寻找删除包含多行字符串中特定字符串的行之前的每一行的方法,如下所示:

string1 
string2
string3
==== bump
string4
string5
string6
==== bump

但只有第一个匹配一个......

最后,我希望将其作为输出:

==== bump
string4
string5
string6
==== bump
4

4 回答 4

1
import re
text = '''\
string1 
string2
string3
==== bump
string4
string5
string6
==== bump'''

print(re.split(r'(=== bump)', text, maxsplit=1)[-1])

产量

string4
string5
string6
==== bump
于 2013-06-20T14:52:48.867 回答
1
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
于 2013-06-20T14:55:15.847 回答
1

替代语言:使用 Perl 的触发器运算符

假设您已将文本存储在/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
于 2013-06-20T15:13:42.240 回答
0
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))
于 2013-06-20T14:59:02.987 回答