python-regexHow to get a number from a string with regex in Python?
Regex (Regular Expression) is a powerful tool for string manipulation in Python. It can be used to extract a number from a string.
Example code
import re
string = 'The number is 1234'
# Extract the number
number = re.findall('\d+', string)
# Print the number
print(number)
Output example
['1234']
Code explanation
import re
: imports the regex modulere.findall('\d+', string)
: searches for one or more digits in the string and returns a list of matchesprint(number)
: prints the extracted number
Helpful links
More of Python Regex
- How to perform a zero length match with Python Regex?
- How to match a year with Python Regex?
- How to match one or more occurence in Python regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a URL using Python regex?
- How to replace in a file using Python regex?
- How to replace a certain group using Python regex?
- How to match a plus sign in Python regex?
- How to match HTML tags with regex in Python?
See more codes...