擅长:python、mysql、java
<p><code>str.replace()</code><sup><a href="https://docs.python.org/2/library/stdtypes.html#str.replace" rel="noreferrer">v2</a><a href="https://docs.python.org/3/library/stdtypes.html#str.replace" rel="noreferrer">v3</a></sup>不识别正则表达式。</p>
<p>要使用正则表达式执行替换,请使用<code>re.sub()</code><sup><a href="https://docs.python.org/2/library/re.html#re.sub" rel="noreferrer">v2</a>| <a href="https://docs.python.org/3/library/re.html#re.sub" rel="noreferrer">v3</a></sup>。</p>
<p>例如:</p>
<pre><code>import re
line = re.sub(
r"(?i)^.*interfaceOpDataFile.*$",
"interfaceOpDataFile %s" % fileIn,
line
)
</code></pre>
<p>在循环中,最好先编译正则表达式:</p>
<pre><code>import re
regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
# do something with the updated line
</code></pre>