【问题标题】:Java : How do I check if any number(0 - 9) is present or not only after a minus(-) char in String?Java:如何仅在字符串中的减号(-)字符之后检查是否存在任何数字(0 - 9)?
【发布时间】:2017-05-09 19:34:49
【问题描述】:

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

【问题讨论】:

标签: java logic operators


【解决方案1】:

你可以这样做:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      这样你就可以匹配a = "-78",也可以匹配a = "anything-78"

      【讨论】:

      • 另外,如何使用a = "operator-78" 来实现,运算符可以是`'+'、'-'、'*'或'/'`
      • 这应该可以完成工作:boolean matches = s.matches("[-+*/]-\\d+");
      • 不是每个运算符后面都需要逗号吗?
      • 不,语法是这样的。如果在其中添加逗号作为分隔符,则在匹配过程中将接受逗号字符:) 它称为字符类或字符集。看看这个:regular-expressions.info/charclass.html
      【解决方案4】:

      你可以用这样的简单代码来做到这一点:

      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.
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-15
        • 2015-04-05
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多