负整数,不包含0

2024-06-23 21:23:41 437
负整数正则表达式与解析,包含各语言使用案例

正则表达式

^-[1-9]\d*$

解释

  • ^:匹配字符串的开始。
  • -?:匹配零个或一个负号。
  • [1-9]:匹配第一位是非零数字(1-9)。
  • \d*:匹配零个或多个数字(0-9)。
  • $:匹配字符串的结束。

各种编程语言中的用法

Python

import re

pattern = r'^-[1-9]\d*$'
test_string = "-123"

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

JavaScript

const pattern = /^-[1-9]\d*$/;
const testString = "-123";

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 = "^-[1-9]\\d*$";
        String testString = "-123";
        
        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 = "^-[1-9]\\d*$";
        string testString = "-123";
        
        if (Regex.IsMatch(testString, pattern)) {
            Console.WriteLine("匹配成功");
        } else {
            Console.WriteLine("匹配失败");
        }
    }
}

PHP

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

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

Ruby

pattern = /^-[1-9]\d*$/
test_string = "-123"

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