我在应用程序中加载了一个字符串,它可以从数字变成字母等等。我有一个简单的if语句,看看它是否包含字母或数字,但是,有些东西不太正确。下面是一个片段。

String text = "abc"; 
String number; 

if (text.contains("[a-zA-Z]+") == false && text.length() > 2) {
    number = text; 
}

虽然文本变量包含字母,但条件返回为true。和&&应该eval作为两个条件都必须为真,以便处理number =文本;

==============================

解决方案:

我能够通过使用以下代码来解决这个问题,该代码由对这个问题的评论提供。所有其他帖子也是有效的!

我使用的有效方法来自第一条评论。尽管提供的所有示例代码似乎也是有效的!

String text = "abc"; 
String number; 

if (Pattern.matches("[a-zA-Z]+", text) == false && text.length() > 2) {
    number = text; 
}

当前回答

Apache Commons Lang提供了stringutils . isnumeric (CharSequence cs),它接受String作为参数,并检查它是否由纯数字字符组成(包括来自非拉丁脚本的数字)。如果存在空格、减号、加号等字符,以及逗号和点等小数分隔符,则该方法返回false。

该类的其他方法允许进一步的数值检查。

其他回答

下面的正则表达式可以用来检查字符串是否只有数字:

如果(str.matches(”。*[^ 0 - 9]。*”))或者(str.matches(”。* \ \ d . * "))

如果String包含非数字,上述两个条件都将返回true。在false时,字符串只有数字。

boolean isNum = text.chars()。allMatch(c -> c >= 48 && c <= 57)

import java.util.*;

class Class1 {
    public static void main(String[] argh) {
        boolean ans = CheckNumbers("123");
        if (ans == true) {
            System.out.println("String contains numbers only");
        } else {
            System.out.println("String contains other values as well");

        }
    }


    public static boolean CheckNumbers(String input) {
        for (int ctr = 0; ctr < input.length(); ctr++) {
            if ("1234567890".contains(Character.valueOf(input.charAt(ctr)).toString())) {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }
}
Character first_letter_or_number = query.charAt(0);
                //------------------------------------------------------------------------------
                if (Character.isDigit())
                {

                }
                else if (Character.isLetter())
                {

                }

您也可以使用NumberUtil。isCreatable(String str)来自Apache Commons