我是python和正则表达式(regex newbie here)的新手,我有以下简单的字符串:
s=r"""99-my-name-is-John-Smith-6376827-%^-1-2-767980716"""
Run Code Online (Sandbox Code Playgroud)
我想只提取上面字符串中的最后一位数字,即767980716,我想知道如何使用python正则表达式实现这一点.
我想做类似的事情:
re.compile(r"""-(.*?)""").search(str(s)).group(1)
Run Code Online (Sandbox Code Playgroud)
表示我想找到介于两者之间的东西(.*?),以" - "开头并以字符串结尾结束 - 但这不会返回任何内容.
我想知道是否有人能指出我正确的方向..谢谢.
phi*_*hag 34
您可以使用re.match
仅查找字符:
>>> import re
>>> s=r"""99-my-name-is-John-Smith-6376827-%^-1-2-767980716"""
>>> re.match('.*?([0-9]+)$', s).group(1)
'767980716'
Run Code Online (Sandbox Code Playgroud)
或者,re.finditer
同样适用:
>>> next(re.finditer(r'\d+$', s)).group(0)
'767980716'
Run Code Online (Sandbox Code Playgroud)
所有正则表达式组件的说明:
.*?
是一个非贪婪的比赛,只消耗尽可能多(贪婪的比赛将消耗除最后一个数字之外的所有内容).[0-9]
并且\d
是捕获数字的两种不同方式.请注意,后者也匹配其他写入方案中的数字,如୪或2.()
)使表达式的内容成为一个组,可以使用group(1)
(或第二组为2,整个匹配为0)检索.+
表示多个条目(末尾至少有一个数字).$
仅匹配输入的结尾.很好,很简单findall
:
import re
s=r"""99-my-name-is-John-Smith-6376827-%^-1-2-767980716"""
print re.findall('^.*-([0-9]+)$',s)
>>> ['767980716']
Run Code Online (Sandbox Code Playgroud)
正则表达式说明:
^ # Match the start of the string
.* # Followed by anthing
- # Upto the last hyphen
([0-9]+) # Capture the digits after the hyphen
$ # Upto the end of the string
Run Code Online (Sandbox Code Playgroud)
或者更简单地只是匹配字符串末尾的数字 '([0-9]+)$'
你的Regex
应该是(\d+)$
.
\d+
用于匹配数字(一个或多个)$
用于匹配字符串的结尾.所以,你的代码应该是: -
>>> s = "99-my-name-is-John-Smith-6376827-%^-1-2-767980716"
>>> import re
>>> re.compile(r'(\d+)$').search(s).group(1)
'767980716'
Run Code Online (Sandbox Code Playgroud)
而且你不需要在str
这里使用函数,因为s
它已经是一个字符串.
我一直在尝试其中的几种解决方案,但如果字符串末尾没有数字,许多解决方案似乎都会失败。下面的代码应该可以工作。
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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28755 次 |
最近记录: |