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>If there is always 3 groups of characters and each group start's with a single letter and has 3 digits after that, and only the last group might have brackets, this expression might be just what you need:</p>

<pre><code>w = 'w123 o456 (t789)'
clean = re.sub(r'^.*(\w\d{3})[ -]+(\w\d{3})[ -]+(\(?\w\d{3}\)?).*$', r'\1 \2 \3', w)
</code></pre>

<p><code>clean</code> now prints <code>'w123 o456 (t789)'</code> even if there are some other characters at the beginning or end of string.</p>

<p>This expression look's for 3 groups of characters each consisting of a letter and 3 digits. For the last group there are optional brackets - <code>\(?</code> and <code>\)?</code>. All characters before and after the 3 groups are matched with <code>^.*</code> and <code>.*$</code>. Then we replace everything with just the 3 captured groups - <code>\1 \2 \3</code></p>

python regex