返回
正则表达式教程:浮点数匹配
正则表达式
2024-02-28 16:09:03
一、正则解释
正则表达式:
^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9]\d*|0\.0+)$
解释:
^
锚定字符串开头。-?[1-9]\d*\.\d+
匹配正数小数,即:-
可选的负号。[1-9]
匹配 1 到 9 的数字。\d*
匹配任意数量的数字。.
匹配小数点。\d+
匹配小数点后至少一位数字。
|-?0\.\d*[1-9]\d*
匹配负数小数,即:-
可选的负号。0\.\d*
匹配小数点开头,并后面跟任意数量的数字。[1-9]\d*
匹配小数点后至少一位数字。
|0\.0+
匹配 0,但排除 0.0。$
锚定字符串结尾。
二、使用场景
该正则表达式可用于匹配浮点数,例如:
- 财务数据
- 科学计算
- 数据验证
三、代码示例
JavaScript
const regex = /^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9]\d*|0\.0+)$/;
const test = '1.23,-1.01,0.00';
console.log(regex.test(test)); // true
Java
import java.util.regex.Pattern;
public class FloatMatcher {
public static void main(String[] args) {
String regex = "^(-?[1-9]\\d*\\.\\d+|-?0\\.\\d*[1-9]\\d*|0\\.0+)import java.util.regex.Pattern;
public class FloatMatcher {
public static void main(String[] args) {
String regex = "^(-?[1-9]\\d*\\.\\d+|-?0\\.\\d*[1-9]\\d*|0\\.0+)$";
String test = "1.23,-1.01,0.00";
boolean matches = Pattern.matches(regex, test);
System.out.println(matches); // true
}
}
quot;;
String test = "1.23,-1.01,0.00";
boolean matches = Pattern.matches(regex, test);
System.out.println(matches); // true
}
}
PHP
<?php
$regex = "/^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9]\d*|0\.0+)$/";
$test = '1.23,-1.01,0.00';
if (preg_match($regex, $test)) {
echo "匹配成功";
} else {
echo "匹配失败";
}
Python
import re
regex = "^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9]\d*|0\.0+)import re
regex = "^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9]\d*|0\.0+)$"
test = '1.23,-1.01,0.00'
match = re.search(regex, test)
if match:
print("匹配成功")
else:
print("匹配失败")
quot;
test = '1.23,-1.01,0.00'
match = re.search(regex, test)
if match:
print("匹配成功")
else:
print("匹配失败")