擅长:python、mysql、java
<p>您可以指定一个函数来执行以下操作:</p>
<pre><code>def replace(match):
return '-' if match.group().isspace() else ''
re.sub(r'[^\w]', replace, string)
</code></pre>
<p>演示:</p>
<pre><code>>>> import re
>>> def replace(match):
... return '-' if match.group().isspace() else ''
...
>>> string = "Felix's 3D's"
>>> re.sub(r'[^\w]', replace, string)
'Felixs-3Ds'
</code></pre>
<p>从<a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow">docs</a>:</p>
<blockquote>
<p><code>re.sub(pattern, repl, string, count=0, flags=0)</code></p>
<p>...</p>
<p>If <code>repl</code> is a function, it is called for every non-overlapping
occurrence of pattern. The function takes a single match object
argument, and returns the replacement string.</p>
</blockquote>
<p>因此,<code>replace</code>将接收每个匹配,并返回<code>'-'</code>(如果它是空格),否则返回<code>''</code>。你知道吗</p>