整数

2024-06-23 21:23:15 411
这个正则表达式用于匹配整数,可以是零、正整数或负整数,包含Python、JavaScript、Java、C#、PHP、Ruby用法示例。

正则表达式

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

解析

  • ^:匹配字符串的开始。
  • (?: ... ):非捕获组,匹配但不捕获括号内的内容。
  • 0:匹配单个字符 0
  • |:逻辑或,表示前后两部分中的任意一个都可以匹配。
  • *(?:-?[1-9]\d)**:非捕获组,用来匹配非零整数。
    • -?:匹配零个或一个负号。
    • [1-9]:匹配1到9之间的任意一个数字。
    • \d*:匹配零个或多个数字(0-9)。
  • $:匹配字符串的结束。

示例

匹配成功的示例:

  • "0"
  • "123"
  • "-123"
  • "456"

匹配失败的示例:

  • "01"(不符合非零开头)
  • "-0"(负号不应跟在零前)
  • "abc"(非数字)

用法

Python

import re

pattern = r'^(?:0|(?:-?[1-9]\d*))$'
test_strings = ["0", "123", "-123", "01", "-0", "abc"]

for test_string in test_strings:
    if re.match(pattern, test_string):
        print(f"'{test_string}': 匹配成功")
    else:
        print(f"'{test_string}': 匹配失败")

JavaScript

const pattern = /^(?:0|(?:-?[1-9]\d*))$/;
const testStrings = ["0", "123", "-123", "01", "-0", "abc"];

testStrings.forEach(testString => {
    if (pattern.test(testString)) {
        console.log(`'${testString}': 匹配成功`);
    } else {
        console.log(`'${testString}': 匹配失败`);
    }
});

Java

import java.util.regex.*;

public class RegexTest {
    public static void main(String[] args) {
        String pattern = "^(?:0|(?:-?[1-9]\\d*))$";
        String[] testStrings = {"0", "123", "-123", "01", "-0", "abc"};
        
        for (String testString : testStrings) {
            if (Pattern.matches(pattern, testString)) {
                System.out.println("'" + testString + "': 匹配成功");
            } else {
                System.out.println("'" + testString + "': 匹配失败");
            }
        }
    }
}

C#

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string pattern = @"^(?:0|(?:-?[1-9]\d*))$";
        string[] testStrings = {"0", "123", "-123", "01", "-0", "abc"};
        
        foreach (string testString in testStrings) {
            if (Regex.IsMatch(testString, pattern)) {
                Console.WriteLine($"'{testString}': 匹配成功");
            } else {
                Console.WriteLine($"'{testString}': 匹配失败");
            }
        }
    }
}

PHP

<?php
$pattern = '/^(?:0|(?:-?[1-9]\d*))$/';
$testStrings = ["0", "123", "-123", "01", "-0", "abc"];

foreach ($testStrings as $testString) {
    if (preg_match($pattern, $testString)) {
        echo "'$testString': 匹配成功\n";
    } else {
        echo "'$testString': 匹配失败\n";
    }
}
?>

Ruby

pattern = /^(?:0|(?:-?[1-9]\d*))$/
test_strings = ["0", "123", "-123", "01", "-0", "abc"]

test_strings.each do |test_string|
  if pattern.match?(test_string)
    puts "'#{test_string}': 匹配成功"
  else
    puts "'#{test_string}': 匹配失败"
  end
end