Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python extracting all numbers from a string using regular expressions

Python extracting all numbers from a string using regular expressions

Document Object Reference Manual Python3 Examples

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

)

print

(

numbers

)

Code analysis:

  1. import re: import Python's regular expression module.
  2. text = "The price is 45 dollars and 30 cents.": define a string containing numbers.
  3. re.findall(r'd+', text): When using re.findall() function to find all substrings in the string matching the regular expression d+ .d+ means matching one or more consecutive digits.
  4. print(numbers): output all the extracted numbers.

Output result:

['45', '30']

Document Object Reference Manual Python3 Examples