擅长:python、mysql、java
<p>那怎么办:</p>
<pre><code>^([^;]+);[\r\n]*([^;]+);[\r\n]*([^;]+);
</code></pre>
<p>替换为:</p>
<pre><code>\1;\2;\3;
</code></pre>
<p><a href="https://regex101.com/r/VpCwKF/1" rel="nofollow noreferrer">regex101</a></p>
<p><a href="https://ideone.com/Z1Bv9B" rel="nofollow noreferrer">run here</a></p>
<pre><code>import re
regex = r"^([^;]+);[\r\n]*([^;]+);[\r\n]*([^;]+);"
test_str = ("New York City; Iron Man; no superpowers;\n"
"Metropolis; Superman; superpowers;\n"
"New York City;\n"
"Spider-Man;\n"
"superpowers;\n"
"Gotham; Batman; no superpowers;\n"
"New York City; Doctor Strange; superpowers;\n\n")
subst = "\\1;\\2;\\3;"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.DOTALL)
if result:
print (result)
</code></pre>