返回

正则表达式教程:数字/货币金额(支持负数、千分位分隔符)

正则表达式

一、正则解释

^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$
  • ^-?\d{1,3} :匹配一个可选的负号 (-),后跟 1 到 3 位数字。
  • (,\d{3})*: :匹配零个或多个逗号分隔的千位组,每个组包含 3 位数字。
  • (.\d{1,2})? :匹配一个可选的小数点 (.),后跟 1 到 2 位小数。

二、使用场景

此正则表达式可用于:

  • 验证数字或货币金额输入
  • 从文本中提取数字数据
  • 格式化货币金额,添加千分位分隔符

三、代码示例

JavaScript

const regex = /^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$/;
const testString = "100,-0.99,3,234.32,-1,900,235.09,12,345,678.90";
const matches = testString.match(regex);
console.log(matches);

Java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {

    public static void main(String[] args) {
        String regex = "^-?\\d{1,3}(,\\d{3})*(\\.\\d{1,2})?
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {

    public static void main(String[] args) {
        String regex = "^-?\\d{1,3}(,\\d{3})*(\\.\\d{1,2})?$";
        String testString = "100,-0.99,3,234.32,-1,900,235.09,12,345,678.90";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(testString);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}
quot;
; String testString = "100,-0.99,3,234.32,-1,900,235.09,12,345,678.90"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(testString); while (matcher.find()) { System.out.println(matcher.group()); } } }

PHP

<?php
$regex = "/^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$/";
$testString = "100,-0.99,3,234.32,-1,900,235.09,12,345,678.90";
preg_match_all($regex, $testString, $matches);
print_r($matches);
?>

Python

import re

regex = r"^-?\d{1,3}(,\d{3})*(\.\d{1,2})?
import re

regex = r"^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$"
testString = "100,-0.99,3,234.32,-1,900,235.09,12,345,678.90"
matches = re.findall(regex, testString)
print(matches)
quot;
testString = "100,-0.99,3,234.32,-1,900,235.09,12,345,678.90" matches = re.findall(regex, testString) print(matches)