import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class regextest {
/* 题目:校验商品价格的正则表达式
* 目的:校验输入的商品价格:不能为(负数或001这样的数字),其他正整数或小数均为true
* 正则说明:"\\d\\.\\d*|[1-9]\\d*|\\d*\\.\\d*|\\d"
* \ :为转义字符
* \d :表示0-9的数字
* [1-9] : 1-9的数字
* [^0] :非零的数字
* * :0次或多次
* | :选择符,分隔不同的匹配方案
* . :表示 "." 符号
* [^-] : 非负号
* */
/**
* @param price 非String类型的数据,可以通过重载 拓展校验的方法
* @return
*/
public static boolean checkPrice(String price){
String regex = "\\d\\.\\d*|[1-9]\\d*|\\d*\\.\\d*|\\d";
Pattern pattern = Pattern.compile(regex); //将给定的正则表达式编译到模式中。
Matcher isNum = pattern.matcher(price);//创建匹配给定输入与此模式的匹配器。
boolean matches = isNum.matches();//如果匹配成功,则可以通过 start、end 和 group 方法获取更多信息.
return matches;
}
public static void main(String[] args) {
// 测试结果:
String orginal = "0";
// String orginal = "0.0"; true
// String orginal = "1"; true
// String orginal = "0.1"; true
// String orginal = "1.01"; true
// String orginal = "123"; true
// String orginal = "123.001"; true
// String orginal = "-1"; false
// String orginal = "-123.0"; false
// String orginal = "01"; false
// String orginal = "001"; false
boolean matches = checkPrice(orginal);
System.out.println(matches);//0 : true
}
}java校验商品价格的正则表达式
最新推荐文章于 2022-08-10 16:58:48 发布
该Java代码示例展示了如何使用正则表达式校验商品价格的有效性,确保价格不为负数或非正常形式(如001)。正则表达式`\d\.\d*|[1-9]\d*|\d*\.\d*|\d`用于匹配正整数或小数。方法`checkPrice`接收一个字符串参数并返回匹配结果。
3857

被折叠的 条评论
为什么被折叠?



