我在应用程序中加载了一个字符串,它可以从数字变成字母等等。我有一个简单的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; 
}

当前回答

我是这样做的:

if(text.matches("^[0-9]*$") && text.length() > 2){
    //...
}

$将避免部分匹配,例如;1 b。

其他回答

你可以使用正则表达式。匹配

if(text.matches("\\d*")&& text.length() > 2){
    System.out.println("number");
}

或者你可以使用像Integer.parseInt(String)或更好的Long.parseLong(String)这样的onversions来获得更大的数字 比如:

private boolean onlyContainsNumbers(String text) {
    try {
        Long.parseLong(text);
        return true;
    } catch (NumberFormatException ex) {
        return false;
    }
} 

然后用:

if (onlyContainsNumbers(text) && text.length() > 2) {
    // do Stuff
}

在这样的典型场景中涉及任何异常抛出/处理是一种糟糕的实践。 因此,parseInt()不是很好,但regex是一个优雅的解决方案,但要注意以下几点: 分数 消极的数字 -十进制分隔符可能因国家而异(例如:','或'。') -有时允许使用所谓的千位分隔符,如空格或逗号,例如12324,1000.355

要处理应用程序中所有必要的情况,您必须小心,但是这个正则表达式涵盖了典型的场景(正/负和分数,用一个点分隔):^[-+]?\d*.?美元\ d + 对于测试,我推荐regexr.com。

使用Java 8流和lambda的解决方案

String data = "12345";
boolean isOnlyNumbers = data.chars().allMatch(Character::isDigit);

亚当·博德罗吉的略有修改版本:

public class NumericStr {


public static void main(String[] args) {
    System.out.println("Matches: "+NumericStr.isNumeric("20"));         // Should be true
    System.out.println("Matches: "+NumericStr.isNumeric("20,00"));          // Should be true
    System.out.println("Matches: "+NumericStr.isNumeric("30.01"));          // Should be true
    System.out.println("Matches: "+NumericStr.isNumeric("30,000.01"));          // Should be true
    System.out.println("Matches: "+NumericStr.isNumeric("-2980"));          // Should be true
    System.out.println("Matches: "+NumericStr.isNumeric("$20"));            // Should be true
    System.out.println("Matches: "+NumericStr.isNumeric("jdl"));            // Should be false
    System.out.println("Matches: "+NumericStr.isNumeric("2lk0"));           // Should be false
}

public static boolean isNumeric(String stringVal) {
    if (stringVal.matches("^[\\$]?[-+]?[\\d\\.,]*[\\.,]?\\d+$")) {
        return true;
    }

    return false;
}
}

今天不得不使用这个,所以刚刚发布了我的修改。包括货币、千位逗号或句号符号,以及一些验证。不包括其他货币符号(欧元、分),验证逗号为每三位数。

这是我的代码,希望对你有所帮助!

 public boolean isDigitOnly(String text){

    boolean isDigit = false;

    if (text.matches("[0-9]+") && text.length() > 2) {
        isDigit = true;
    }else {
        isDigit = false;
    }

    return isDigit;
}