如何检测python字符串中的最后一位数字

dan*_*nny 3 regex string python-2.7

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

Chr*_*our 6

这是一种使用方法re.sub

import re

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

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

输出:

534
12
86
Run Code Online (Sandbox Code Playgroud)

解释:

该函数采用 a regular expression、 areplacement stringstring您想要替换的:re.sub(regex,replace,string)

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

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

所以我们要更换整个字符串只有我们有兴趣在获取的号码在Python中,我们需要使用原始字符串这样的:r'\1'。如果字符串不以数字结尾,则返回一个空字符串。


twosixfour = "get_the_numb3r_2_^_64__18446744073709551615"

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

>>> 18446744073709551615
Run Code Online (Sandbox Code Playgroud)