Python正则表达式:从字符串中获取末尾数字

31

我对Python和正则表达式都比较新(这里是正则表达式新手),我有一个简单的字符串:

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

我想从上述字符串中提取最后的数字,即767980716,并且我想知道如何使用Python正则表达式来实现此目标。

我想按照以下方式进行类似的操作:

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

我想查找以"-"开头并以字符串结尾的内容,位于(.*?)之间 - 但是这返回了空值。

请问是否有人能指点一下方向。谢谢。

7个回答

43

您可以使用re.match仅查找字符:

>>> import re
>>> s=r"""99-my-name-is-John-Smith-6376827-%^-1-2-767980716"""
>>> re.match('.*?([0-9]+)$', s).group(1)
'767980716'

或者,re.finditer同样有效:

>>> next(re.finditer(r'\d+$', s)).group(0)
'767980716'

所有正则表达式组件的解释:

  • .*?非贪心匹配,尽可能少地消耗字符(贪婪匹配会消耗除最后一个数字以外的所有内容)。
  • [0-9]\d 是两种捕获数字的不同方式。请注意,后者还可以匹配其他书写方案中的数字,比如 ୪ 或 ൨。
  • 括号 (()) 将表达式的内容分组,可以用group(1)(或2表示第二个组,0 表示整个匹配)检索该组。
  • + 表示多个条目(末尾至少有一个数字)。
  • $ 仅匹配输入的结尾。

8

使用findall函数简单方便:

import re

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

print re.findall('^.*-([0-9]+)$',s)

>>> ['767980716']

正则表达式解释:

^         # 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

或者更简单地匹配字符串末尾的数字 '([0-9]+)$'


7

你的正则表达式应为(\d+)$

  • \d+用于匹配数字(一个或多个)
  • $用于匹配字符串末尾。

因此,你的代码应该是:-

>>> s = "99-my-name-is-John-Smith-6376827-%^-1-2-767980716"
>>> import re
>>> re.compile(r'(\d+)$').search(s).group(1)
'767980716'

在这里您不需要使用 str 函数,因为 s 已经是一个字符串。


2
如果您将正则表达式模式编写为r'(\d+)$',那么您就不必转义反斜杠。 - Sam Mussmann

4

把正则表达式留给需要更大量的工作的事情。

>>> def parse_last_digits(line): return line.split('-')[-1]
>>> s = parse_last_digits(r"99-my-name-is-John-Smith-6376827-%^-1-2-767980716")
>>> s
'767980716'

4
使用以下正则表达式:
\d+$

$ 表示字符串结束。

\d 表示数字。

+ 匹配前一个字符 1 次或多次。


3

我一直在尝试使用多种解决方案,但许多方案似乎会在字符串结尾没有数字时失败。以下代码应该可以正常工作。

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)

1
m = re.findall(r"\d+\s*$", W); last_digits = m[0] if m else 'None' 可以消除冗余的表达式匹配。 - Todd

2

尝试使用\d+$代替。这将匹配一个或多个数字字符,后跟字符串的结尾。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接