java正则表达式:验证字符串数字

时间:2023-02-12 18:46:48

 正则表达式:^([0-9]+)$ -> ^:匹配以0-9开头,[0-9]:匹配0-9数字,+:匹配至少一个数字,$:匹配以数字结尾

/**
*正则表达式:验证字符串数字
*两种方式:
*1.pattern.matcher(number.trim()).find()
*2.Pattern.matches(numberRegexp,number.trim())
*
*/
public static boolean matchNumber(String number) {
boolean result = false;
if (number!=null) {
final String numberRegexp = "^([0-9]+)$";
try {
Pattern pattern
= Pattern.compile(numberRegexp);
if (pattern.matcher(number.trim()).find()) {
result
= true;
}

/*if (Pattern.matches(numberRegexp,number.trim())) {
result = true;
}
*/
}
catch (Exception e) {
result
= false;
}
}
else {
result
= false;
}
return result;
}