正整数,包含0

2024-06-23 21:17:34 165
包含0的正整数正则表达式与解析

正则表达式

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

解释

  • ^:匹配字符串的开始。
  • (0|[1-9]\d*):匹配字符0或以非零数字开头的数字序列。
    • 0:匹配数字0。
    • [1-9]:匹配非零数字(1-9)。
    • \d*:匹配零个或多个数字(0-9)。
  • $:匹配字符串的结束。

用法

Python

import re

pattern = r'^(0|[1-9]\d*)$'
test_string = "0"

if re.match(pattern, test_string):
    print("匹配成功")
else:
    print("匹配失败")

JavaScript

const pattern = /^(0|[1-9]\d*)$/;
const testString = "0";

if (pattern.test(testString)) {
    console.log("匹配成功");
} else {
    console.log("匹配失败");
}

Java

import java.util.regex.*;

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

C#

using System;
using System.Text.RegularExpressions;

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

PHP

<?php
$pattern = '/^(0|[1-9]\d*)$/';
$testString = "0";

if (preg_match($pattern, $testString)) {
    echo "匹配成功";
} else {
    echo "匹配失败";
}
?>

Ruby

pattern = /^(0|[1-9]\d*)$/
test_string = "0"

if pattern.match?(test_string)
  puts "匹配成功"
else
  puts "匹配失败"
end