繁体   English   中英

python正则表达式:从字符串中获取结束数字

[英]python regex: get end digits from a string

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

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

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

我想做类似的事情:

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

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

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

您可以使用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 表示整个匹配)。
  • +表示多个条目(末尾至少有一个数字)。
  • $仅匹配输入的结尾。

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]+)$'末尾的数字

你的正则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'

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

使用下面的正则表达式

\d+$

$表示字符串的结尾..

\\d是一个数字

+匹配前面的字符 1 到多次

为需要更多繁重工作的东西保存正则表达式。

>>> 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'

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

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM