62,614
社区成员
发帖
与我相关
我的任务
分享
String str = "ss0.11";
Pattern pattern = Pattern.compile("^-?[1-9]\\d*$");
Matcher matcher = pattern.matcher(str);
if(matcher.find()) {
System.out.println("整形");
}else if(Pattern.compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$").matcher(str).find()){
System.out.println("浮点型");
}else {
System.out.println("字符型");
}
/**
* 正则表达式可能不严谨(写的比较唐突)
* @param source
* @return 返回0表示非数值,返回1表示是int型,返回2表示是double型
*/
public static int type(String source){
int result = 0;
String regex1 = "^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$";
boolean flag1 = source.matches(regex1);
if(flag1){
String regex2 = "^[-+]?([0-9]+)$";
boolean flag2 = source.matches(regex2);
if(flag2){
result = 1;
}
else{
result = 2;
}
}
return result;
}
楼主试试效果吧,写的比较唐突,在我这里实验,a,b,c三个字符串分别返回2,1,0 。public static int checkString(String str) {
if (isDigits(str))
return 1;
else if (isNum(str))
return 2;
else
return 0;
}
/**
* 判断字符串是否为数字
*
* @param string
* @return boolean
*/
public static boolean isNumber(String string)
{
for (int i = 0; i < string.length(); i++)
{
if (!Character.isDigit(string.charAt(i)))
{
return false;
}
}
return true;
}
public static boolean isDigits(String str) {
return str.matches("[-+]?[0-9]*");
}