// 示例代码:使用正则表达式匹配数字
// 匹配整数(包括正数和负数)
const integerRegex = /^-?\d+$/;
// 测试整数
console.log(integerRegex.test("123")); // true
console.log(integerRegex.test("-456")); // true
console.log(integerRegex.test("abc")); // false
// 匹配浮点数(包括正数和负数,允许小数点)
const floatRegex = /^-?\d+(\.\d+)?$/;
// 测试浮点数
console.log(floatRegex.test("123.45")); // true
console.log(floatRegex.test("-67.89")); // true
console.log(floatRegex.test("0.123")); // true
console.log(floatRegex.test("123")); // true (整数也是有效的浮点数)
console.log(floatRegex.test("abc")); // false
// 解释:
// - ^ 表示字符串的开始
// - $ 表示字符串的结束
// - \d 表示一个数字字符(0-9)
// - + 表示前面的字符必须出现一次或多次
// - ? 表示前面的字符是可选的(出现0次或1次)
// - (\.\d+)? 表示一个小数部分,小数点后必须跟随一个或多个数字,整个小数部分是可选的
上一篇:js 正则判断
下一篇:js uuid库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站