擅长:python、mysql、java
<p>您已经在组中捕获了预期的数据,现在可以使用<code>re.sub</code>将整个匹配替换为group1和group2的内容。在</p>
<p>试试你修改过的Python代码</p>
<pre><code>import re
string = 'a2017a12a'
pattern = re.compile(".*(20[0-9]{2}).?(0[1-9]|1[0-2]).*")
result = re.sub(pattern, r'\1\2', string)
print(result)
</code></pre>
<p>请注意,我是如何在模式周围添加<code>.*</code>,这样数据周围的任何额外字符都将匹配并删除。此外,删除了不需要的额外括号。这也适用于字符串,在这些字符串周围可能有其他数字,例如<code>hello123 a2017a12a some other 99 numbers</code></p>
<p>输出</p>
^{pr2}$
<p><strong><a href="https://regex101.com/r/icR99Y/1" rel="nofollow noreferrer">Regex Demo</a></strong></p>