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 replace all using Python regex?
- How to count matches with Python regex?
- How to match a year with Python Regex?
- How to perform a zero length match with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...