检查字符串是否包含“+”符号和数字

时间:2015-11-13 09:25:04

标签: android

我有String,有时值已更改:

String str1 = "+25"; // only have "+" sign and number

String str2 = "+Name"; // only have "+" sign and text

我如何区分这些String,因为我想做类似的事情:

if (isString1Type) { // both strings also have "+" sign
// do something
}

String是否具有此案例的任何功能。 谁能给我建议?

3 个答案:

答案 0 :(得分:2)

是的,你可以这样做:

 String str = "+Name";
 boolean hasPlusSign = str.contains("+");
 boolean isNumber = tryParseInt(str.replace("+", ""));
 if(hasPlusSign && isNumber){ //if the string is +25 for example here will be true, else it will go to the else statement
    //do something
} else {
    //something else
}


boolean tryParseInt(String value) {  
   try {  
       Integer.parseInt(value);  
       return true;  
    } catch (NumberFormatException e) {  
       return false;  
    }  
}

答案 1 :(得分:1)

您可以使用简单的正则表达式"[+][0-9]+"。它更简单容易 这是示例代码

   String str1 = "+25";
    if (str1.matches("[+][0-9]+")){
        // your string contains plus "+" and number
        // do something
    }eles{

    }

希望这个帮助

答案 2 :(得分:0)

你可以使用这样的正则表达式:

[0-9] +此处+表示0-9以内的多个数字

String str1 = "+25"; 

String str2 = "+Name"; 

String regex = "[0-9]+";

if(isDigit(str1.replace("+",""))){
  Log.d("str1","Integer");
}else{
  Log.d("str1","Not Integer");   
  }

if(isDigit(str2.replace("+",""))){
  Log.d("str2","Integer");
}else{
  Log.d("str2","Not Integer");
 }

boolean isDigit(String str){
  if(str.matches(regex)){
            return true;
        }else {
           return false;
        }
 }