简体   繁体   中英

Remove everything before space using regular expression in python

Suppose I have a string: 997 668, now I need to remove anything before space ie I need 668 as the output. I need a solution using regular expression. Now I am using the below:

x = '997 668'
x  = x.split(' ')[1]

Above also give the output but fails when there is only one number, if x = 555 then output comes blank which I dont want.

Instead of getting the first of one item or the second of two items, simply get the last item with [-1] :

>>> '996 668'.split()[-1]
'668'
>>> '668'.split()[-1]
'668'

Your own code would work if you were a bit more defensive

try:
   x = '997 668'
   x  = x.split(' ')[1]
except IndexError:
   x = x[0]

If your input has multiple spaces, such as

235 989 877

then your question is somewhat ambiguous because you don't say whether you want to remove everything before the first space or everything before the last space.

TigerhawkT3's answer removes everything before the last space.

If you want to remove everything before the first space, you need the second parameter to split and do it this way:

>>> '996 668'.split(' ', 1)[-1]
'668'
>>> '996'.split(' ', 1)[-1]
'996'
>>> '996 351 980 221'.split(' ', 1)[-1]
'351 980 221'

Note that TigerhawkT3's answer (which is great, by the way) gives you the answer under the other interpretation:

>>> '996 351 980 221'.split()[-1]
'221'

Depends on what you want.

Just don't use a regex. :)

Regex solution:

import re
re.findall('\d+', x)[-1]

re.findall always returns a list so you can avoid your IndexError without using an exception catcher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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