返回

正则表达式教程:整数匹配

正则表达式

一、正则解释

正则表达式 /^(?:0|(?:-?[1-9]\d*))$/用于匹配整数,具体解释如下:

  • ^ :匹配字符串的开头。
  • (?:0) :匹配数字0。
  • | :或运算符,表示匹配0或以下模式。
  • (?:-?[1-9]\d)* :
    • -? :匹配可选的负号。
    • [1-9] :匹配数字1到9(不包括0)。
    • *\d ** :匹配0个或更多数字。
  • $ :匹配字符串的结尾。

二、使用场景

此正则表达式可以用于以下场景:

  • 验证用户输入的数字是否为整数。
  • 从文本中提取整数数据。
  • 过滤出列表中仅包含整数的元素。

三、代码示例

JavaScript

const regex = /^(?:0|(?:-?[1-9]\d*))$/;

const testCases = ["-1231", "123", "0"];

testCases.forEach((testCase) => {
  const match = regex.test(testCase);
  console.log(`${testCase} is a valid integer: ${match}`);
});

Java

import java.util.regex.Pattern;

public class IntegerMatcher {

    public static void main(String[] args) {
        String regex = "^(?:0|(?:-?[1-9]\\d*))
import java.util.regex.Pattern;

public class IntegerMatcher {

    public static void main(String[] args) {
        String regex = "^(?:0|(?:-?[1-9]\\d*))$";
        Pattern pattern = Pattern.compile(regex);

        String[] testCases = {"-1231", "123", "0"};

        for (String testCase : testCases) {
            boolean match = pattern.matcher(testCase).matches();
            System.out.println(testCase + " is a valid integer: " + match);
        }
    }
}
quot;
; Pattern pattern = Pattern.compile(regex); String[] testCases = {"-1231", "123", "0"}; for (String testCase : testCases) { boolean match = pattern.matcher(testCase).matches(); System.out.println(testCase + " is a valid integer: " + match); } } }

PHP

<?php

$regex = "/^(?:0|(?:-?[1-9]\d*))$/";

$testCases = ["-1231", "123", "0"];

foreach ($testCases as $testCase) {
    $match = preg_match($regex, $testCase);
    echo "$testCase is a valid integer: " . ($match ? 'true' : 'false') . "\n";
}

Python

import re

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

regex = r"^(?:0|(?:-?[1-9]\d*))$"

testCases = ["-1231", "123", "0"]

for testCase in testCases:
    match = re.match(regex, testCase)
    print(f"{testCase} is a valid integer: {bool(match)}")
quot;
testCases = ["-1231", "123", "0"] for testCase in testCases: match = re.match(regex, testCase) print(f"{testCase} is a valid integer: {bool(match)}")