Java:如何在字符串中的减号( - )字符后检查是否存在任何数字(0 - 9)?

时间:2016-12-24 10:45:39

标签: java logic operators

假设我有一个字符串a。我想检查a是否包含减号后的数字。前,a="-78"; 如果a仅在减号( - )后面有一个数字(此处为7),那么我可以根据该值返回truefalse

4 个答案:

答案 0 :(得分:0)

你可以这样做:

return a.matches("-\\d+");

答案 1 :(得分:0)

你可以用startsWith()方法检查字符串:

 String a =  0;
 a="-78";

 // Starts with
 boolean  b = string.startsWith("-7"); // return true

答案 2 :(得分:0)

  

假设我有一个字符串a。我想检查是否包含   减号后面的数字。 ex,a =“ - 78”;

boolean matches = s.matches(".*-\\d+");

使用此功能,您可以与a = "-78"匹配,也可以与a = "anything-78"

匹配

答案 3 :(得分:0)

你可以用这样的简单代码来实现:

String a = "-78";
int b = a.indexOf("-");
if(b == -1)
    //there is no "-".
else {
    int c = a.charAt(b+1);
    if(c >= 48 && c <= 57)
        // there is a "-" and after that you have a number.
}