在 Python 中只从字符串中获取第一个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32571348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:50:07  来源:igfitidea点击:

getting only the first Number from String in Python

pythonstringnumbers

提问by Serious Ruffy

I′m currently facing the problem that I have a string of which I want to extract only the first number. My first step was to extract the numbers from the string.

我目前面临的问题是我有一个我只想提取第一个数字的字符串。我的第一步是从字符串中提取数字。

Headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
print (re.findall('\d+', headline ))
Output is ['27184', '2']

In this case it returned me two numbers but I only want to have the first one "27184".

在这种情况下,它返回了两个数字,但我只想拥有第一个“27184”。

Hence, I tried with the following code:

因此,我尝试使用以下代码:

 print (re.findall('/^[^\d]*(\d+)/', headline ))

But It does not work:

但它不起作用:

 Output:[]

Can you guys help me out? Any feedback is appreciated

你们能帮我吗?任何反馈表示赞赏

采纳答案by Avinash Raj

Just use re.searchwhich stops matching once it finds a match.

只需使用re.searchwhich 一旦找到匹配就停止匹配。

re.search(r'\d+', headline).group()

or

或者

You must remove the forward slashes present in your regex.

您必须删除正则表达式中存在的正斜杠。

re.findall(r'^\D*(\d+)', headline)

回答by Dylan Lawrence

re.search('[0-9]+', headline).group()

回答by David

Solution without regex (not necessarily better):

没有正则表达式的解决方案(不一定更好):

import string

no_digits = string.printable[10:]

headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
trans = str.maketrans(no_digits, " "*len(no_digits))

print(headline.translate(trans).split()[0])
>>> 27184