<p>一个简单的方法是找到下一个“探索”字。但是如果由于任何原因,字符串值包含这个词,您将得到错误的结果。当字符串包含嵌套的方括号时,如果尝试停止使用花括号,也会出现同样的问题。你知道吗</p>
<p>这就是为什么我建议对字符串的语法进行更精确的描述,考虑字符串和嵌套的花括号。由于re模块没有递归功能(用于处理嵌套结构),因此我将使用<a href="https://pypi.org/project/regex/" rel="nofollow noreferrer">pypi/regex</a>模块:</p>
<pre><code>import regex
pat = r'''(?xms)
\b explore:
[^\S\r\n]* # optional horizontal whitespaces
[^\n{]* # possible content of the same line
# followed by two possibilities
(?: # the content stops at the end of the line with a ;
; [^\S\r\n]* $
| # or it contains curly brackets and spreads over eventually multiple lines
( # group 1
{
[^{}"]*+ # all that isn't curly brackets nor double quotes
(?:
" [^\\"]*+ (?: \\. [^\\"]* )*+ " # contents between quotes
[^{}"]*
|
(?1) # nested curly brackets, recursion in the group 1
[^{}"]*
)*+
}
)
)'''
results = [x.group(0) for x in regex.finditer(pat, yourstring)]
</code></pre>
<p><a href="https://regex101.com/r/v2LFVD/3" rel="nofollow noreferrer">demo</a></p>
<p>更严格地说,您可以添加对单引号字符串的支持,还可以防止模式开头的“explore:”不在使用<code>(*SKIP)(*FAIL)</code>构造的字符串中。你知道吗</p>