识别字符串Java中的数字和特殊字符

时间:2014-09-29 14:54:17

标签: java string numbers character special-characters

我有一个问题:

我在Java代码中有两个字符串:

1) hello
2) 01234

我想实现一个知道如何识别字符串“01234”仅包含数字或特殊字符(例如。,*,?或其他字符串)并且字符串“hello”仅由字符串字符组成的代码

我该如何实施?

1 个答案:

答案 0 :(得分:2)

一种可能的方法是使用正则表达式,例如“\ d +”将只检查数字。

String regex = "\\d+";
System.out.println("123".matches(regex)); // <-- true, 123 is all digits.

但是,这并未解决您的特殊字符。因此,更清晰的解决方案可能是使用Character.isLetter(char)等等,

public static boolean isLetters(String in) {
    if (in != null) {
        for (char ch : in.toCharArray()) {
            if (!Character.isLetter(ch)) {
                return false;
            }
        }
    }
    return true;
}

然后您的isDigits()测试看起来像,

public static boolean isDigitsOrSpecial(String in) {
    if (in != null) {
        for (char ch : in.toCharArray()) {
            if (Character.isLetter(ch)) {
                return false;
            }
        }
    }
    return true;
}