How to remove everything after the last number in a string
<p>I have strings like this:</p>

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

<p>My goal is to remove everything after the last number, so my desired output would be</p>

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

<p>It is not always the same ending, so <code>-- --</code> is just one example.</p>

<pre><code>import re

re.sub('(.*?)(\d)', '', w)
</code></pre>

<p>gives me</p>

<pre><code>'-- --'
</code></pre>

<p>How can I modify the command so that it removes this part?</p>

<p>The point is that your expression contains <em>lazy</em> dot matching pattern and it matches up to and including the first one or more digits.</p>

<p>You need to use <em>greedy</em> dot matching pattern to match up to the <em>last</em> digit, and capture that part into a capturing group. Then, use a <code>r'\1'</code> backreference in the replacement pattern to restore  the value in the result.</p>

<p>This will work with 1-line strings:</p>

<pre><code>re.sub(r'(.*\d).*', r'\1', w)
</code></pre>

<p>or with anchors and also supporting strings with linebreaks:</p>

<pre><code>re.sub(r'^(.*\d).*$', r'\1', w, flags=re.S)
</code></pre>

<p><a href="https://ideone.com/hX5aTY" rel="nofollow">Python demo:</a></p>

<pre><code>import re
w = 'w123 o456 t789-- --'
print(re.sub(r'^(.*\d).*$', r'\1', w, flags=re.S))
# =&gt; w123 o456 t789
</code></pre>

python regex