简体   繁体   English

如何删除字符串中最后一个数字之后的所有内容

[英]How to remove everything after the last number in a string

I have strings like this: 我有这样的字符串:

w = 'w123 o456 t789-- --'

My goal is to remove everything after the last number, so my desired output would be 我的目标是删除最后一个数字之后的所有内容,因此我想要的输出将是

w123 o456 t789

It is not always the same ending, so -- -- is just one example. 它的结局并不总是相同的,所以-- --只是一个例子。

import re

re.sub('(.*?)(\d)', '', w)

gives me 给我

'-- --'

How can I modify the command so that it removes this part? 如何修改命令,以便删除此部分?

You can use: 您可以使用:

>>> w = 'w123 o456 t789-- --'
>>> re.sub(r'\D+$', '', w)
'w123 o456 t789'

\\D+$ will remove 1 or more non-digit characters before end anchor $ . \\D+$将删除结尾锚$之前的1个或多个非数字字符。

The point is that your expression contains lazy dot matching pattern and it matches up to and including the first one or more digits. 关键是您的表达式包含惰性点匹配模式,并且匹配到并且包括前一个或多个数字。

You need to use greedy dot matching pattern to match up to the last digit, and capture that part into a capturing group. 您需要使用贪婪点匹配模式来匹配最后一位,并将该部分捕获到捕获组中。 Then, use a r'\\1' backreference in the replacement pattern to restore the value in the result. 然后,在替换模式中使用r'\\1'引用来恢复结果中的值。

This will work with 1-line strings: 这将适用于1行字符串:

re.sub(r'(.*\d).*', r'\1', w)

or with anchors and also supporting strings with linebreaks: 或带有锚点以及带有换行符的字符串:

re.sub(r'^(.*\d).*$', r'\1', w, flags=re.S)

Python demo: Python演示:

import re
w = 'w123 o456 t789-- --'
print(re.sub(r'^(.*\d).*$', r'\1', w, flags=re.S))
# => w123 o456 t789
st = 'w123 o456 t789-- --'
print st.rstrip()
"w123 o456 t789'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM