2017-03-25 94 views
0

我想在字符串上执行一个代码块如果是的话不是只包含整数。例如,如果输入是,则什么都不会发生;否则如果它是2017abc,代码块将被执行。检查一个字符串是否不仅包含整数

我已经尝试过正则表达式^[0-9]+$,但它好像if (!keyword.matches("/^[0-9]+$/")不工作,因为我希望它。我检查了多个在线资源,我很确定这个正则表达式是正确的。

我失去了一些东西在这里?


更新:

解决使用keywords.replaceAll("\\d", "").length() > 0问题。但仍然不确定为什么上述不起作用。

无论如何,多亏了早些时候提出这个答案的人。 :)

+0

试试这个链接:http://stackoverflow.com/questions/10575624/java-string-see-if-a-string-contains-only-numbers-and-not-letters –

+0

匹配'\ D'会只匹配字符串中的非数字。 – ClasG

回答

0

正确的正则表达式可能是.*[^0-9].*。如果matches()返回true,则比您需要执行的操作为真。

0

试试这个

import java.util.Scanner; 
    public class NotOnlyIntegers 
    { 
     public static void main(String[] args) 
     { 
      Scanner scan = new Scanner(System.in); 
      System.out.println("Please enter the String"); 
      String test=scan.nextLine(); 

      int digit=0; 
      int letter=0; 
      for(int x=0;x<test.length()-1;++x) 
      { 
       if(Character.isDigit(test.charAt(x))) 
       { 
        ++digit; 
       } 
       else if(Character.isLetter(test.charAt(x))) 
       { 
        ++letter; 
       } 
      } 
      if(digit>0&&letter>0) 
      { 
       System.out.println("Code Executed"); 
      } 
      else 
      System.out.println("Code Not Executed"); 
     } 

    } 
0

它不漂亮,但为什么不让的Java做的工作:

private boolean isInteger(String o){ 
    try{ 
     Integer.valueOf(o); 
     return true; 
    }catch(NumberFormatException ex){ 
     return false; 
    } 

} 
+0

我的if语句已经在try-catch块中,所以我想避免使用这个 – hopeweaver

+0

抛出和捕获异常是有代价的。 http://stackoverflow.com/questions/36343209/which-part-of-throwing-an-exception-is-expensive – LppEdd

1

您在更新中规定的解决办法看起来不错。不过,我会试着解决你对初始代码不起作用的好奇心。

我测试了您的问题声明中给出的正则表达式:

^[0-9] + $

而且这似乎为我工作的罚款。根据我的快速研究,问题可能出现在您后面提到的问题中的java代码中。不需要在开始和结束时使用斜杠。

替换此

if (!keyword.matches("/^[0-9]+$/") 

与此

if (!keyword.matches("^[0-9]+$") 

,你是好去。很高兴知道我是否错过了一些东西。

有关正则表达式和模式的广泛知识,我推荐下面的链接。

http://www.vogella.com/tutorials/JavaRegularExpressions/article.html#regular-expressions

好运。

相关问题