Regex 使用Python正则表达式从字符串末尾获取10个数字?

Regex 使用Python正则表达式从字符串末尾获取10个数字?,regex,python-2.7,Regex,Python 2.7,我有一些字符串,比如- 1. "07870 622103" 2. "(0) 07543 876545" 3. "07321 786543 - not working" 我想得到这些字符串的最后10位。像- 1. "07870622103" 2. "07543876545" 3. "07321786543" 到目前为止,我已经试过- a = re.findall(r"\d+${10}", mobilePhone) 请帮忙 只需过滤字符串中的数字并挑出最后10个数字就更容易了: ''.join

我有一些字符串,比如-

1. "07870 622103"
2. "(0) 07543 876545"
3. "07321 786543 - not working"
我想得到这些字符串的最后10位。像-

1. "07870622103"
2. "07543876545"
3. "07321786543"
到目前为止,我已经试过-

a = re.findall(r"\d+${10}", mobilePhone)

请帮忙

只需过滤字符串中的数字并挑出最后10个数字就更容易了:

''.join([c for c in mobilePhone if c.isdigit()][-10:])
结果:

>>> mobilePhone = "07870 622103"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7870622103'
>>> mobilePhone = "(0) 07543 876545"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7543876545'
>>> mobilePhone = "07321 786543 - not working"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7321786543'
正则表达式方法(过滤除数字以外的所有内容)速度更快,不过:

$ python -m timeit -s "mobilenum='07321 786543 - not working'" "''.join([c for c in mobilenum if c.isdigit()][-10:])"
100000 loops, best of 3: 6.68 usec per loop
$ python -m timeit -s "import re; notnum=re.compile(r'\D'); mobilenum='07321 786543 - not working'" "notnum.sub(mobilenum, '')[-10:]"
1000000 loops, best of 3: 0.472 usec per loop

只需过滤字符串中的数字并挑出最后10个数字,就会更容易:

''.join([c for c in mobilePhone if c.isdigit()][-10:])
结果:

>>> mobilePhone = "07870 622103"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7870622103'
>>> mobilePhone = "(0) 07543 876545"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7543876545'
>>> mobilePhone = "07321 786543 - not working"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7321786543'
正则表达式方法(过滤除数字以外的所有内容)速度更快,不过:

$ python -m timeit -s "mobilenum='07321 786543 - not working'" "''.join([c for c in mobilenum if c.isdigit()][-10:])"
100000 loops, best of 3: 6.68 usec per loop
$ python -m timeit -s "import re; notnum=re.compile(r'\D'); mobilenum='07321 786543 - not working'" "notnum.sub(mobilenum, '')[-10:]"
1000000 loops, best of 3: 0.472 usec per loop

我建议使用正则表达式来丢弃所有非数字。像这样:

newstring = re.compile(r'\D').sub('', yourstring)
正则表达式非常简单-
\D
表示非数字。上面的代码使用
sub
将任何非数字字符替换为空字符串。因此,您可以在
newstring

哦,最后十个字符使用
newstring[-10:]


这是一个正则表达式的答案。Martijn Pieters的答案可能更像Python。

我建议使用正则表达式扔掉所有非数字。像这样:

newstring = re.compile(r'\D').sub('', yourstring)
正则表达式非常简单-
\D
表示非数字。上面的代码使用
sub
将任何非数字字符替换为空字符串。因此,您可以在
newstring

哦,最后十个字符使用
newstring[-10:]


这是一个正则表达式的答案。Martijn Pieters的答案可能更像pythonic。

您的输出每个包含11位数字。您的输出每个包含11位数字。两者中速度越快,pythonic越强;你的方法是更快的,两种方法中速度越快,就越像蟒蛇;你的方法更快。