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

在Python中仅从字符串中获取第一个数字,python,string,numbers,Python,String,Numbers,我目前面临的问题是,我有一个字符串,我只想提取其中的第一个数字。我的第一步是从字符串中提取数字 Headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')" print (re.findall('\d+', headline )) Output is ['27184', '2'] 在本例中,它返回了两个数字,但我只想要第一个“27184” 因此,我尝试使用以下代码: print (re.findall('/^[^\d]*(\

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

Headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
print (re.findall('\d+', headline ))
Output is ['27184', '2']
在本例中,它返回了两个数字,但我只想要第一个“27184”

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

 print (re.findall('/^[^\d]*(\d+)/', headline ))
但它不起作用:

 Output:[]

你们能帮帮我吗?欢迎任何反馈

只要使用
重新搜索
,一旦找到匹配项就停止匹配

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

必须删除正则表达式中的正斜杠

re.findall(r'^\D*(\d+)', headline)
不带正则表达式的解决方案(不一定更好):


在我的例子中,我想得到字符串中的第一个数字和货币,我尝试了所有的解决方案,一些返回没有点的数字,另一些返回我这样做的数字

priceString = "Rs249.5"

def advancedSplit(unformatedtext):
    custom_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    priceList = []
    str_length = len(unformatedtext)
    index = 0
    for l in range(len(unformatedtext)):
        if unformatedtext[l] in custom_numbers:
            price = unformatedtext[slice(l, len(unformatedtext))]
            currency = unformatedtext[slice(0,l)]
            priceList.append(currency)
            priceList.append(price)
            break
        elif index == str_length:
            priceList.append("")
            priceList.append("unformatedtext")
            break
        else:
            continue
            
        index += 1
    return priceList
print(advancedSplit(priceString))

为了确保列表始终具有2的长度,我添加了elif,以防价格字符串仅为“249.5”,因为我在web scrape中使用它。
>re.search(r'\d+',Headline)。组(0)'27184'
打印(re.findall(r'.[^\d]*(\d+),Headline))
您使用的是查找所有出现的
findall
。顺便说一下,Python正则表达式不需要
/
字符。谢谢你们的反馈。太好了,成功了
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
priceString = "Rs249.5"

def advancedSplit(unformatedtext):
    custom_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    priceList = []
    str_length = len(unformatedtext)
    index = 0
    for l in range(len(unformatedtext)):
        if unformatedtext[l] in custom_numbers:
            price = unformatedtext[slice(l, len(unformatedtext))]
            currency = unformatedtext[slice(0,l)]
            priceList.append(currency)
            priceList.append(price)
            break
        elif index == str_length:
            priceList.append("")
            priceList.append("unformatedtext")
            break
        else:
            continue
            
        index += 1
    return priceList
print(advancedSplit(priceString))