返回
正则表达式教程:匹配负整数(不包含 0)
正则表达式
2024-02-28 16:08:39
一、正则解释
正则表达式:/^-[1-9]\d*$/
解释:
- ^: 表示字符串的开头。
- -: 表示负号。
- [1-9]: 匹配数字 1 到 9,排除 0。
- \d:* 匹配 0 个或多个数字字符。
- $: 表示字符串的结尾。
总的来说,此正则表达式匹配以负号 (-) 开头,后跟一个或多个数字,且不包含 0 的字符串。
二、使用场景
此正则表达式可用于以下场景:
- 验证表单输入以确保输入负整数。
- 从文本中提取负整数。
- 在数据处理中过滤或查找负整数。
三、代码示例
JavaScript
const regex = /^-[1-9]\d*$/;
console.log(regex.test("-1231")); // true
console.log(regex.test("0")); // false
console.log(regex.test("123")); // false
Java
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern regex = Pattern.compile("^-[1-9]\\d*import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern regex = Pattern.compile("^-[1-9]\\d*$");
System.out.println(regex.matcher("-1231").matches()); // true
System.out.println(regex.matcher("0").matches()); // false
System.out.println(regex.matcher("123").matches()); // false
}
}
quot;);
System.out.println(regex.matcher("-1231").matches()); // true
System.out.println(regex.matcher("0").matches()); // false
System.out.println(regex.matcher("123").matches()); // false
}
}
PHP
$regex = "/^-[1-9]\d*$/";
echo preg_match($regex, "-1231") . "\n"; // 1
echo preg_match($regex, "0") . "\n"; // 0
echo preg_match($regex, "123") . "\n"; // 0
Python
import re
regex = r"^-[1-9]\d*import re
regex = r"^-[1-9]\d*$"
print(re.match(regex, "-1231") is not None) # True
print(re.match(regex, "0") is not None) # False
print(re.match(regex, "123") is not None) # False
quot;
print(re.match(regex, "-1231") is not None) # True
print(re.match(regex, "0") is not None) # False
print(re.match(regex, "123") is not None) # False