擅长:python、mysql、java
<p>我不认为regexp是最好的方法,但是对于那些好奇的人来说,可以这样做:</p>
<pre><code>def expr(m):
out = []
for item in m.group(1).split(','):
a, b = map(str.strip, item.split('='))
out.append('<%s>%s</%s>' % (a, b, a))
return '\n'.join(out)
rr = r'\(([^()]*)\)'
while re.search(rr, data):
data = re.sub(rr, expr, data)
</code></pre>
<p>基本上,我们反复用xml块替换最下面的括号<code>(no parens here)</code>,直到不再有括号为止。为了简单起见,我还将主表达式包含在括号中,如果不是这样,只需在解析之前执行<code>data='(%s)' % data</code>。在</p>