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".
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
Making use of isdigit() function to extract digits from a Python string. Python provides us with string. isdigit() to check for the presence of digits in a string. Python isdigit() function returns True if the input string contains digit characters in it.
To get the first digit, we can use the Python math log10() function. In the loop example, we divided by 10 until we got to a number between 0 and 10. By using the log10() function, we can find out exactly how many times we need to divide by 10 and then do the division directly.
This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
Just use re.search
which stops matching once it finds a match.
re.search(r'\d+', headline).group()
or
You must remove the forward slashes present in your regex.
re.findall(r'^\D*(\d+)', headline)
re.search('[0-9]+', headline).group()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With