Python extracting all numbers from a string using regular expressions
In Python, we can use re module to handle regular expressions. To extract all numbers from a string, you can use re.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
)
(
numbers
)
Code analysis:
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): When usingre.findall()function to find all substrings in the string matching the regular expressiond+.d+means matching one or more consecutive digits.print(numbers): output all the extracted numbers.
Output result:
['45', '30']
Python3 Examples