在 Python 中只从字符串中获取第一个数字 [英] getting only the first Number from String in Python
本文介绍了在 Python 中只从字符串中获取第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前面临的问题是我有一个字符串,我只想提取其中的第一个数字.我的第一步是从字符串中提取数字.
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']
在这种情况下,它返回了两个数字,但我只想拥有第一个27184".
In this case it returned me two numbers but I only want to have the first one "27184".
因此,我尝试使用以下代码:
Hence, I tried with the following code:
print (re.findall('/^[^\d]*(\d+)/', headline ))
但它不起作用:
Output:[]
你们能帮帮我吗?任何反馈表示赞赏
Can you guys help me out? Any feedback is appreciated
推荐答案
只需使用 re.search
,它会在找到匹配项后停止匹配.
Just use re.search
which stops matching once it finds a match.
re.search(r'\d+', headline).group()
或
您必须删除正则表达式中的正斜杠.
You must remove the forward slashes present in your regex.
re.findall(r'^\D*(\d+)', headline)
这篇关于在 Python 中只从字符串中获取第一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文