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