<p>你可以通过</p>
<pre><code>import re
string = """
** Hardware [0/1]
- [ ] adapt a programmable motor to a tripod to be used for panning
** Reading - Technology [1/6]
- [X] Introduction to Networking - Charles Severance
- [ ] A Tour of C++ - Bjarne Stroustrup
- [ ] C++ How to Program - Paul Deitel
- [X] Computer Systems - Randal Bryant
- [ ] The C programming language - Brian Kernighan
- [ ] Beginning Linux Programming -Matthew and Stones
** Reading - Health [3/4]
- [ ] Patrick McKeown - The Oxygen Advantage
- [X] Total Knee Health - Martin Koban
- [X] Supple Leopard - Kelly Starrett
- [X] Convict Conditioning 1 and 2
"""
def getitems(section):
rx = re.compile(r'^\*{2} ' + re.escape(section) + r'.+[\n\r](?P<block>(?:(?!^\*{2})[\s\S])+)', re.MULTILINE)
try:
items = rx.search(string)
return items.group('block')
except:
return None
items = getitems('Reading - Technology')
print(items)
</code></pre>
<p>看看<a href="http://ideone.com/57dzQK" rel="nofollow noreferrer"><strong>working on ideone.com</strong></a>。<br/>
</p><hr/>
代码的核心是(浓缩的)表达式:
<pre><code>^\*{2}.+[\n\r] # match the beginning of the line, followed by two stars, anything else in between and a newline
(?P<block> # open group "block"
(?: # non-capturing group
(?!^\*{2}) # a neg. lookahead, making sure no ** follows at the beginning of a line
[\s\S] # any character...
)+ # ...at least once
) # close group "block"
</code></pre>
<p>在实际代码的<code>**</code>之后插入搜索字符串。请参见<strong><a href="https://regex101.com/r/CHt4Wl/1" rel="nofollow noreferrer">regex101.com</a></strong>上的<code>Reading - Technology</code>演示。
</p><hr/>
作为后续操作,您也可以只返回<strong>所选值,如下所示:
<pre><code>def getitems(section, selected=None):
rx = re.compile(r'^\*{2} ' + re.escape(section) + r'.+[\n\r](?P<block>(?:(?!^\*{2})[\s\S])+)', re.MULTILINE)
try:
items = rx.search(string).group('block')
if selected:
rxi = re.compile(r'^ - \[X\]\ (.+)', re.MULTILINE)
try:
selected_items = rxi.findall(items)
return selected_items
except:
return None
return items
except:
return None
items = getitems('Reading - Health', selected=True)
print(items)
</code></pre>