python-regexHow to match a float with regex in Python?
Matching a float with regex in Python can be done using the re
module. The following example code block shows how to match a float with regex:
import re
float_regex = re.compile(r'[+-]?\d*\.\d+')
float_match = float_regex.match('3.14')
print(float_match.group())
The output of the example code is:
3.14
Code explanation
import re
: imports there
module which provides regular expression matching operations.float_regex = re.compile(r'[+-]?\d*\.\d+')
: compiles a regular expression pattern to match a float. The pattern[+-]?\d*\.\d+
matches a float with an optional sign (+ or -), followed by any number of digits, followed by a decimal point, followed by one or more digits.float_match = float_regex.match('3.14')
: uses the compiled regular expression pattern to match the string3.14
.print(float_match.group())
: prints the matched float.
Helpful links
More of Python Regex
- How to match a UUID using Python regex?
- How to get all matches from a regex in Python?
- How to get a group from a regex in Python?
- How to match whitespace in Python regex?
- How to split using Python regex?
- How to replace in a file using Python regex?
- How to remove special characters using Python regex?
- How to match any symbol except a given one with Python regex?
- How to remove numbers from a string using Python regex?
- How to replace a certain group using Python regex?
See more codes...