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 match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match whitespace in Python regex?
- How to match a URL using Python regex?
- How to replace all using Python regex?
- How to match a UUID using Python regex?
- How to split using Python regex?
- How to remove numbers from a string using Python regex?
- How to replace a certain group using Python regex?
See more codes...