/^(?:0|(?:-?[1-9]\d*))$
0
。"0"
"123"
"-123"
"456"
"01"
(不符合非零开头)"-0"
(负号不应跟在零前)"abc"
(非数字)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}': 匹配失败")
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}': 匹配失败`);
}
});
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 + "': 匹配失败");
}
}
}
}
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
$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";
}
}
?>
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