擅长:python、mysql、java
<p>这是另一个解决方案(我还使用“非贪婪”修饰符重写regex,将<code>?</code>放在<code>*</code>之后,因为我发现它更可读)。你知道吗</p>
<p><code>r"\1"</code>引用的组是以parenthises作为未命名的组来完成的。还将<code>re.compile</code>用作样式首选项以减少arg的数量:</p>
<pre><code>line = "I go to Bridgebrook i go out <ERR targ=sometimes> some times </ERR> on Tuesday night i go to Youth <ERR targ=club> clob </ERR> ."
select_text_regex = re.compile(r"<ERR targ=(.*?)>.*?<\/ERR>")
select_text_regex.sub(r"\1", line)
</code></pre>
<p>命名组备选方案:</p>
<pre><code>line = "I go to Bridgebrook i go out <ERR targ=sometimes> some times </ERR> on Tuesday night i go to Youth <ERR targ=club> clob </ERR> ."
select_text_regex = re.compile(r"<ERR targ=(?P<to_replace>.*?)>.*?<\/ERR>")
select_text_regex.sub(r"\g<to_replace>", line)
</code></pre>
<p>您可以在这里找到一些关于组引用的文档:</p>
<p><a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow noreferrer">https://docs.python.org/3/library/re.html#regular-expression-syntax</a></p>