我有以下案文:
[red]
aaa [bbb] hello
[blue]
aaa
[green]
ccc我想提取各节标题之间的所有文本。我尝试了从特定节头到另一个标头列表中匹配的前瞻性断言:
keys = ('red', 'blue', 'green')
for key in keys:
match = re.search(r'\[' + key + r'\](.*)(?=(?:' + '|'.join(keys) + r'|$))',
text, flags=re.DOTALL)
print(key, match.group(1))不过,我漏掉了一些东西,因为它与任何东西都不匹配。有什么想法吗?
发布于 2017-04-07 11:58:13
最后,我决定不使用正则表达式来匹配部分内容。
# Walk through the file line by line and collect text from the specific sections
keys = ('red', 'blue', 'green')
last_section = ''
for line in text.splitlines():
if line.startswith('#'):
continue
match = re.match(r'^\[(' + '|'.join(keys) + ')\]', line)
if match:
last_section = match.group(1)
continue
if last_section:
new_contents[last_section] += '\n' + line
for section in new_contents:
new_contents[section] = new_contents[section].strip()发布于 2017-04-07 10:26:36
你能找到的!你可以把你的部分和它中的值组合在一起,
>>> import re
>>> print re.findall(r'\[(\w*)\]([\w \n]*)',text)
[('red', '\n\naaa '), ('bbb', ' hello\n\n'), ('blue', '\n\naaa\n\n'), ('green', '')]这里是您的部分\[(\w*)\]和([\w \n]*),用于您节中的内容。有了这个结果,您可以删除或替换多余的换线!
希望能帮上忙!
发布于 2017-04-07 10:54:46
也许像这样的方法可以奏效:
keys = ('red', 'blue', 'green')
res = re.findall(r'\[\w+\].?|([\w\[\] ]+)', text)
res = [x for x in res if x]
for n in range(len(keys)):
print(keys[n], res[n])结果:
('red', 'aaa [bbb] hello')
('blue', 'aaa')
('green', 'ccc')示例
https://stackoverflow.com/questions/43275114
复制相似问题