擅长:python、mysql、java
<p>如果要匹配可选的<code>Arguments:</code>和<code>Returns:</code>节、<em>和</em>之后的文本,则不想使用<code>(?P<name>...)</code>来命名捕获组,还可以使用<code>(?:...)</code>这是常规括号的非捕获版本。</p>
<p>正则表达式如下所示:</p>
<pre><code>m = re.search('^(.*?)(?:Arguments:(.*?))?(?:Returns:(.*?))?$', doc, re.DOTALL)
# ^^ ^^
</code></pre>
<p>根据Python3<a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p><code>(?:...)</code></p>
<p>A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.</p>
</blockquote>