python正则表达式:从字符串中获取结束数字 [英] python regex: get end digits from a string

查看:191
本文介绍了python正则表达式:从字符串中获取结束数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python 和正则表达式很陌生(这里是正则表达式新手),我有以下简单的字符串:

I am quite new to python and regex (regex newbie here), and I have the following simple string:

s=r"""99-my-name-is-John-Smith-6376827-%^-1-2-767980716"""

我只想提取上述字符串中的最后一位数字,即 767980716,我想知道如何使用 python 正则表达式来实现这一点.

I would like to extract only the last digits in the above string i.e 767980716 and I was wondering how I could achieve this using python regex.

我想做类似的事情:

re.compile(r"""-(.*?)""").search(str(s)).group(1)

表示我想在 (.*?) 之间找到以-"开头并以字符串结尾结尾的内容 - 但这不返回任何内容..

indicating that I want to find the stuff in between (.*?) which starts with a "-" and ends at the end of string - but this returns nothing..

我想知道是否有人能指出我正确的方向..谢谢.

I was wondering if anyone could point me in the right direction.. Thanks.

推荐答案

我已经尝试了几个这样的解决方案,但如果字符串末尾没有数字,许多解决方案似乎都失败了.以下代码应该可以工作.

I have been playing around with several of these solutions, but many seem to fail if there are no numeric digits at the end of the string. The following code should work.

import re

W = input("Enter a string:")
if re.match('.*?([0-9]+)$', W)== None:
    last_digits = "None"
else:
    last_digits = re.match('.*?([0-9]+)$', W).group(1)
print("Last digits of "+W+" are "+last_digits)

这篇关于python正则表达式:从字符串中获取结束数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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