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

当前回答

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

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;
}
}

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

其他回答

这是一个样品。根据需要,只查找字符串和过程形式中的数字。

text.replaceAll("\\d(?!$)", "$0 ");

欲了解更多信息,请查看谷歌文档 https://developer.android.com/reference/java/util/regex/Pattern在这里可以使用Pattern

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

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

在Java中有很多从string中获取数字的工具(反之亦然)。您可能希望跳过正则表达式部分,以避免其复杂化。

例如,你可以试着看看什么是Double。parseDouble(String s)为您返回。如果在字符串中没有找到合适的值,它应该抛出NumberFormatException。我建议使用这种技术,因为实际上可以将String表示的值作为数字类型使用。

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

public class Test{  
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String str;
    boolean status=false;
    System.out.println("Enter the String : ");
    str = sc.nextLine();
    
    char ch[] = str.toCharArray();
    
    for(int i=0;i<ch.length;i++) {
        if(ch[i]=='1'||ch[i]=='2'||ch[i]=='3'||ch[i]=='4'||ch[i]=='5'||ch[i]=='6'||ch[i]=='7'||ch[i]=='8'||ch[i]=='9'||ch[i]=='0') {
            ch[i] = 0;
        }
    }
    
    for(int i=0;i<ch.length;i++) {
        if(ch[i] != 0) {
            System.out.println("Mixture of letters and Digits");
            status = false;
            break;
        }
        else
            status = true;
    }
    
    if(status == true){
        System.out.println("Only Digits are present");
    }
}

}