擅长:python、mysql、java
<p>正则表达式可以通过在模式之前查找字符串的开头或下划线来完成这项工作:</p>
<pre><code>>>> import re
>>> key = 'a-1_tea-1'
>>> re.sub(r'(?:^|(?<=_))a-1', 'a-2', key)
'a-2_tea-1'
>>> key = 'tea-1_a-1'
>>> re.sub(r'(?:^|(?<=_))a-1', 'a-2', key)
'tea-1_a-2'
</code></pre>
<p>有关详细信息,请参阅Python<a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow noreferrer">Regular expression syntax</a>文档</p>