Reg ex remove non alpha characters keeping spaces
<p>I've written a simple function that strips a string of all non-alpha characters keeping spaces in place.</p>

<p>Currently it relies on using two regular expressions. However, in in interest of brevity I'd like to reduce those two reg exs into one. Is this possible?</p>

<pre><code>import re

def junk_to_alpha(s):
  reg = r"[^A-Za-z]"
  p = re.compile(reg)
  s = re.sub(p, " ", s)
  p = re.compile(r"\s+")
  s = re.sub(p, " ", s)
  return s

print junk_to_alpha("Spoons! 12? \/@# ,.1 12 Yeah? {[]}")

# Spoons Yeah
</code></pre>

<p>You may enclose the <code>[^a-zA-Z]+</code> with <code>\s*</code>:</p>

<pre><code>import re

def junk_to_alpha(s):
  s = re.sub(r"\s*[^A-Za-z]+\s*", " ", s)
  return s

print junk_to_alpha("Spoons! 12? \/@# ,.1 12 Yeah? {[]}")
</code></pre>

<p>See the <a href="https://ideone.com/N1pz8v" rel="nofollow">online Python demo</a></p>

<p>The pattern details:</p>

<ul>
<li><code>\s*</code> - zero or more whitespaces</li>
<li><code>[^A-Za-z]+</code> - 1 or more characters other than ASCII letters</li>
<li><code>\s*</code> - see above.</li>
</ul>

python regex string python-2.7