Getting only the first number from a string in Python

Currently, I am facing the problem that I have a string from 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, he returned me two numbers, but I only want to have the first "27184".

Therefore, I tried to use the following code:

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

But this does not work:

  Output:[] 

Can you guys help me? Any feedback is welcome

+7
python string numbers
source share
3 answers

Just use re.search , which stops if it finds a match.

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

or

You must remove the forward slashes present in your regular expression.

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

A 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 
+2
source share
 re.search('[0-9]+', headline).group() 
+1
source share

All Articles