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 in a file using Python regex?
- How to remove special characters using Python regex?
- How to replace all using Python regex?
- How to match a plus sign in Python regex?
- How to match a year with Python Regex?
- How to validate an IP using Python regex?
- How to match zero or one occurence in Python regex?
- How to replace a certain group using Python regex?
- How to match a phone number in Python regex?
- How to use negative lookbehind in Python regex?
See more codes...