我正在尝试提取跨越多行的内容。内容如下所示:
some content here
[1/1/2015 - SSR] something
[1/2/2015 - SSR] another:
*something here
*another something here
not relevant, should not be returned
[1/3/2015 - SSR] another one
*
之前总是有空格我使用的代码是:
re.search(r'.*- SSR](.*)',line,re.DOTALL)
预期输出为:
[1/1/2015 - SSR] something
[1/2/2015 - SSR] another:
*something here
*another something here
[1/3/2015 - SSR] another one
然而,它只检索第一个和第三个记录,而不是第二个记录。因为它的范围是多线的。有人可以帮忙吗?我真的很感激。
答案 0 :(得分:0)
你可以使用这样的正则表达式:
^.*?- SSR]([^[]*)
<强> Working demo 强>
匹配信息:
MATCH 1
1. [34-45] ` something
`
MATCH 2
1. [61-111] ` another:
*something here
*another something here
`
MATCH 3
1. [127-139] ` another one`
您可以使用以下内容:
import re
p = re.compile(ur'^\[.*?- SSR]([^[]*)', re.DOTALL | re.MULTILINE)
test_str = u"some content here\n[1/1/2015 - SSR] something\n[1/2/2015 - SSR] another:\n*something here\n*another something here\n[1/3/2015 - SSR] another one"
re.findall(p, test_str)
另一方面,如果你想捕获组中字符串的开头,那么你可以使用这个正则表达式:
^(\[.*?- SSR][^[]*)
<强> Working demo 强>
匹配信息:
MATCH 1
1. [18-45] `[1/1/2015 - SSR] something
`
MATCH 2
1. [45-111] `[1/2/2015 - SSR] another:
*something here
*another something here
`
MATCH 3
1. [111-139] `[1/3/2015 - SSR] another one`
答案 1 :(得分:0)
假设文本可以包含尖括号,您可以使用整个前导码和非捕获前瞻来获取内容。最后一条记录需要\Z
到最后。
import re
s = """[1/1/2015 - SSR] something
[1/2/2015 - SSR] another:
*something here
*another something here
[1/3/2015 - SSR] another one"""
print 'string to process'
print s
print
print 'matches'
matches = re.findall(
r'\[\d+/\d+/\d+ - SSR\].*?(?:(?=\[\d+/\d+/\d+ - SSR\])|\Z)',
s, re.MULTILINE|re.DOTALL)
for i, match in enumerate(matches, 1):
print "%d: %s" % (i, match.strip())
输出
string to process
[1/1/2015 - SSR] something
[1/2/2015 - SSR] another:
*something here
*another something here
[1/3/2015 - SSR] another one
matches
1: [1/1/2015 - SSR] something
2: [1/2/2015 - SSR] another:
*something here
*another something here
3: [1/3/2015 - SSR] another one