检查字符串中的非数字字符

Har*_*rsH 5 java regex

我想检查String是否只包含数字字符,还是包含字母数字字符.

我必须在数据库事务中实现此检查,其中将获取大约十万条记录并通过此检查,因此我需要优化的性能答案.

请帮忙.

目前,我已经通过Try-Catch Block实现了这一点:在try块中解析Integer中的字符串并检查catch块中的NumberFormatException.如果我错了,请建议.

提前致谢.

San*_*nda 25

您可以使用正则表达式进行检查.

假设(仅限数值):

String a = "493284835";
a.matches("^[0-9]+$"); // returns true
Run Code Online (Sandbox Code Playgroud)

假设(仅限字母数字值):

String a = "dfdf4932fef84835fea";
a.matches("^([A-Za-z]|[0-9])+$"); // returns true
Run Code Online (Sandbox Code Playgroud)

正如Pangea在评论区域所说:

如果性能很关键,那么编译正则表达式是首选.请参阅下面的示例:

String a = "dfdf4932fef84835fea";
Pattern pattern = Pattern.compile("^([A-Za-z]|[0-9])+$");
Matcher matcher = pattern.matcher(a);

if (matcher.find()) {
    // it's ok
}
Run Code Online (Sandbox Code Playgroud)

  • 由于性能是主要问题,我建议一次编译正则表达式并重用http://stackoverflow.com/questions/1720191/java-util-regex-importance-of-pattern-compile (5认同)

Jea*_*les 6

只是谷歌搜索,我发现了这个链接

 public boolean containsOnlyNumbers(String str) {        
        //It can't contain only numbers if it's null or empty...
        if (str == null || str.length() == 0)
            return false;

        for (int i = 0; i < str.length(); i++) {

            //If we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i)))
                return false;
        }

        return true;
    }
Run Code Online (Sandbox Code Playgroud)

编辑:要检查数字的RegExp应该是:

return yourNumber.matches("-?\\d+(.\\d+)?");
Run Code Online (Sandbox Code Playgroud)

  • 警告![`isDigit()`](http://download.oracle.com/javase/7/docs/api/java/lang/Character.html#isDigit(char))*不仅仅是*0-9! (3认同)