How to remove everything (except certain characters) after the last number in a string
<p>This is a follow-up of <a href="http://stackoverflow.com/questions/39637955/how-to-remove-everything-after-the-last-number-in-a-string">this question.</a></p>

<p>There I learned how to remove all characters after the last number in a string; so I can turn</p>

<pre><code>w = 'w123 o456 t789-- --'
</code></pre>

<p>into</p>

<pre><code>w123 o456 t789
</code></pre>

<p>Now I might have strings like this:</p>

<pre><code>w = 'w123 o456 (t789)'
</code></pre>

<p>In this case, </p>

<pre><code>re.sub(r'\D+$', '', w)
</code></pre>

<p>would give me</p>

<pre><code>w123 o456 (t789
</code></pre>

<p>So I have then actually two closely related questions:</p>

<p>1) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> in a way that certain characters are kept (e.g. parenthesis)? </p>

<p>2) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> so that only certain characters are removed (e.g. dashes and white spaces)?</p>

<p><strong>EDIT</strong></p>

<p>@Martin Bonner's answer gets very close but e.g. for </p>

<pre><code>w='w123 -o456 t789--) --'
</code></pre>

<p>the command</p>

<pre><code> re.sub('[- ]+$', '', w)
</code></pre>

<p>gives me <code>w123 -o456 t789--)</code> but it should also get rid of the remaining dashes.</p>

<p>To keep certain characters <code>(</code> and <code>)</code> use:</p>

<pre><code>re.sub('[^0-9()]+$', '', w)
</code></pre>

<p>to remove only certain characters from the end of the line:</p>

<pre><code>re.sub('[- ]+$', '', w)
</code></pre>

<p>In square brackets, you can list the characters you want to match.  If the first character is <code>^</code> then everything <em>except</em> the specified characters are matched.  The only minor niggle is that <code>-</code> usually specifies a range (so we can specify, eg, all digits without having to list all 10 of 
them).  That means that if we are going to specify <code>-</code> as one of the characters to match, it needs to go <em>first</em>.  (If you want to specify <code>^</code>, then escape it with <code>\</code> and go back to raw strings.)</p>

<p>From the comment, I think you actually meant the second challenge to be
"remove all the dashes and spaces from the string that lie between the last digit, and the end of the line".  That may be possible with a regular expression, but somebody who comes back to maintain the code in three months time will hate you (and it may well be you).  Just remember the Jamie Zawinski quote:</p>

<blockquote>
  <p>Some people, when confronted with a problem, think âI know, I'll use
  regular expressions.â  Now they have two problems.</p>
</blockquote>

python regex