返回

正则表达式教程:浮点数(严格)

正则表达式

一、正则解释

该正则表达式用于匹配严格的浮点数,即小数点两侧至少有一位数字。

  • ^ : 匹配字符串开头。
  • (-?) : 匹配可选的负号。
  • [1-9]\d *: 匹配一个正整数,后面可以跟任意数量的数字。
  • .\d+ : 匹配一个点号,后面至少跟一位数字。
  • |-?0.\d[1-9]* :匹配一个小数点后没有数字,或者小数点后有数字但第一位数字为 0 的数字。
  • $ : 匹配字符串结尾。

二、使用场景

该正则表达式适用于以下场景:

  • 验证输入的数字是否为严格的浮点数。
  • 从文本中提取严格的浮点数。
  • 执行其他需要严格匹配浮点数的任务。

三、代码示例

JavaScript

const regex = /^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9])$/;
const input = "1.23,-1.01";
const result = regex.test(input);
console.log(result); // true

Java

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String regex = "(-?[1-9]\\d*\\.\\d+|-?0\\.\\d*[1-9])";
        String input = "1.23,-1.01";
        Pattern pattern = Pattern.compile(regex);
        boolean result = pattern.matcher(input).matches();
        System.out.println(result); // true
    }
}

PHP

<?php
$regex = '/^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9])$/';
$input = '1.23,-1.01';
$result = preg_match($regex, $input);
echo $result; // 1
?>

Python

import re

regex = r"^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9])
import re

regex = r"^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9])$"
input = "1.23,-1.01"
result = re.match(regex, input)
print(result) # <re.Match object; span=(0, 5), match='1.23'>
quot;
input = "1.23,-1.01" result = re.match(regex, input) print(result) # <re.Match object; span=(0, 5), match='1.23'>