Python extracts all numbers from a string using regular expressions
In Python, we can useremodule to handle regular expressions. To extract all numbers from a string, you can usere.findall()function, which can return all substrings matching the regular expression.
Example
import re
# Example string
text = "The price is 45 dollars and 30 cents."
# Use regular expressions to extract all numbers
numbers = re.findall(r'd+', text)
print(numbers)
# Example string
text = "The price is 45 dollars and 30 cents."
# Use regular expressions to extract all numbers
numbers = re.findall(r'd+', text)
print(numbers)
Code explanation:
import re: Import Python's regular expression module.text = "The price is 45 dollars and 30 cents.": Define a string containing numbers.re.findall(r'd+', text): Usere.findall()function to find in the string all substrings that match the regular expressiond+substrings.d+Indicates matching one or more consecutive digits.print(numbers): Output all the extracted numbers.
Output result:
['45', '30']Other extensions
Python3 Examples