擅长:python、mysql、java
<p>可以将<code>re.sub</code>与<a href="http://www.regular-expressions.info/refcapture.html" rel="nofollow">capturing groups</a>一起使用,如下所示:</p>
<pre><code>>>> import re
>>> s="""text
... $$ math $$
...
... $$
... math
... $$
...
... text $$math$$ text"""
>>> print re.sub(r'\$\$\s?(\w+)\s?\$\$',r'\[\1\]',s)
text
\[math\]
\[math\]
text \[math\] text
</code></pre>
<p><code>\1</code>是正则表达式模式中匹配的第一个组,在本例中<code>(\w+)</code></p>
<p>编辑:如果你在<code>$$</code>之间有更多的文本,当你添加到你的编辑中时,你只需要改变<code>\w</code>与<code>.+</code>匹配的单词字符来匹配任何长度超过1的字符。你知道吗</p>
<pre><code>>>>re.sub(r'\${2,}\s?(.+?)\s?\${2,}',r'[\1]',s)
</code></pre>