Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write a Python regular expression that matches floating point numbers?
This article will discuss how to write a Python regular expression that matches floating point numbers. We will try to create a regular expression pattern that can match any floating point number.
A regular expression for floating point numbers should match integers and floating point numbers where the integer part might be optional. A floating-point number can look like ?
Whole numbers with decimals like 3.14, 1.5, 12.10
Negative numbers like -2.55, -1.003
Numbers with optional zeros like 007.5, .75
Basic Regex Pattern for Floating Point Numbers
Here is the regular expression pattern for identifying floating point numbers ?
import re
# Basic pattern for floating point numbers
pattern = r"[+-]?[0-9]+\.[0-9]+"
print(f"Pattern: {pattern}")
Pattern: [+-]?[0-9]+\.[0-9]+
The above regex pattern components explained ?
- [+-]? − Optional plus (+) or minus (-) sign at the start
- [0-9]+ − At least one digit before the decimal point
- \. − The literal decimal point (escaped)
- [0-9]+ − At least one digit after the decimal point
Enhanced Pattern for More Cases
A more comprehensive pattern that handles edge cases like numbers starting with a decimal ?
import re
# Enhanced pattern that matches more floating point formats
enhanced_pattern = r"[+-]?(?:[0-9]*\.?[0-9]+)"
test_numbers = ["3.14", "-2.5", ".75", "42.", "+1.23", "007.5"]
for num in test_numbers:
if re.fullmatch(enhanced_pattern, num):
print(f"'{num}' is a valid floating point number")
else:
print(f"'{num}' is not matched")
'3.14' is a valid floating point number '-2.5' is a valid floating point number '.75' is a valid floating point number '42.' is a valid floating point number '+1.23' is a valid floating point number '007.5' is a valid floating point number
Validate Floating Numbers in Text
Use re.findall() to extract all floating point numbers from a text string ?
import re
# Define a string with various numbers
text = "Pi is 3.14 and the temperature dropped to -2.5 degrees."
# Define pattern to match floating-point numbers
pattern = r"[+-]?[0-9]+\.[0-9]+"
# Find all matches in the string
matches = re.findall(pattern, text)
print("Floating point numbers found:", matches)
Floating point numbers found: ['3.14', '-2.5']
Validate User Input
Create a function to validate if user input is a valid floating point number ?
import re
def is_float(number_str):
"""Check if string represents a floating point number"""
return bool(re.fullmatch(r"[+-]?[0-9]+\.[0-9]+", number_str))
# Test different inputs
test_inputs = ["12.5", "abc", "-3.14", "42", "1.0"]
for inp in test_inputs:
result = is_float(inp)
print(f"is_float('{inp}') = {result}")
is_float('12.5') = True
is_float('abc') = False
is_float('-3.14') = True
is_float('42') = False
is_float('1.0') = True
Extract Floating Numbers with Units
Extract floating point numbers that are followed by unit letters ?
import re
# String with numbers and units
text = "Measurements: 2.5kg, -1.75m, 50, 10.3cm, 15"
# Pattern to match floats followed by letters (units)
pattern = r"[+-]?[0-9]+\.[0-9]+(?=[a-z%])"
# Find floating numbers with units
numbers_with_units = re.findall(pattern, text)
print("Floating numbers with units:", numbers_with_units)
Floating numbers with units: ['2.5', '-1.75', '10.3']
Comparison of Patterns
| Pattern | Matches | Use Case |
|---|---|---|
[+-]?[0-9]+\.[0-9]+ |
Basic floats with required digits | Simple validation |
[+-]?(?:[0-9]*\.?[0-9]+) |
Floats, integers, decimals starting with dot | Comprehensive matching |
[+-]?[0-9]+\.[0-9]+(?=[a-z%]) |
Floats followed by units | Data with measurements |
Conclusion
Use [+-]?[0-9]+\.[0-9]+ for basic floating point validation. For comprehensive matching including edge cases, use the enhanced pattern. Combine with lookahead assertions when you need to match numbers with specific contexts like units.
