如何检测python字符串中的最后一位数字 [英] How can I detect last digits in python string

查看:157
本文介绍了如何检测python字符串中的最后一位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测字符串中的最后一位数字,因为它们是我的字符串的索引.它们可能是 2^64,所以只检查字符串中的最后一个元素是不方便的,然后尝试第二个......等等.字符串可能类似于 asdgaf1_hsg534,即字符串中也可能是其他数字,但中间有某个位置,它们与我想要获取的索引不相邻.

I need to detect last digits in the string, as they are indexes for my strings. They may be 2^64, So it's not convenient to check only last element in the string, then try second... etc. String may be like asdgaf1_hsg534, i.e. in the string may be other digits too, but there are somewhere in the middle and they are not neighboring with the index I want to get.

推荐答案

这里是一个使用 re.sub 的方法:

Here is a method using re.sub:

import re

input = ['asdgaf1_hsg534', 'asdfh23_hsjd12', 'dgshg_jhfsd86']

for s in input:
    print re.sub('.*?([0-9]*)$',r'\1',s)

输出:

534
12
86

说明:

该函数接受一个正则表达式、一个替换字符串,以及您想要对其进行替换的string:re.sub(regex,replace,string)

The function takes a regular expression, a replacement string, and the string you want to do the replacement on: re.sub(regex,replace,string)

正则表达式 '.*?([0-9]*)$' 匹配整个字符串并捕获字符串末尾之前的数字.括号用于捕获我们感兴趣的匹配部分,\1 指的是第一个捕获组,\2 指的是第二个.

The regex '.*?([0-9]*)$' matches the whole string and captures the number that precedes the end of the string. Parenthesis are used to capture parts of the match we are interested in, \1 refers to the first capture group and \2 the second ect..

.*?      # Matches anything (non-greedy) 
([0-9]*) # Upto a zero or more digits digit (captured)
$        # Followed by the end-of-string identifier 

所以我们只用我们感兴趣的捕获数字替换整个字符串.在python中,我们需要使用原始字符串:r'\1'.如果字符串不以数字结尾,则返回一个空字符串.

So we are replacing the whole string with just the captured number we are interested in. In python we need to use raw strings for this: r'\1'. If the string doesn't end with digits then a blank string with be returned.

twosixfour = "get_the_numb3r_2_^_64__18446744073709551615"

print re.sub('.*?([0-9]*)$',r'\1',twosixfour)

>>> 18446744073709551615

这篇关于如何检测python字符串中的最后一位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆