简体   繁体   English

验证字符串是否只有数字

[英]Validate if string has only numbers

My Java application 'A' is getting mobile number as String from another java application.我的 Java 应用程序“A”正在从另一个 Java 应用程序获取手机号码作为字符串。 So after app A gets the mobile number string, I need to validate if that mobile number String has only numbers in it.因此,在应用程序 A 获取手机号码字符串后,我需要验证该手机号码字符串中是否只有数字。 For validating that I have used a simple logic as below,为了验证我使用了如下简单的逻辑,

public static boolean containsOnlyDigits(String str, int n) {
    for (int i = 1; i < n; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
        }
    }
    return true;
}

I am checking from i=1 as 1st character will be '+' for country code.我正在检查 i=1 作为国家代码的第一个字符将是“+”。 This approach is O(n).这种方法是 O(n)。 There is another approach where we can use Double.parseDouble(str) .还有另一种方法可以使用Double.parseDouble(str) This will throw NumberFormatException so that we can catch and consider it is an Alphanumeric String.这将抛出NumberFormatException以便我们可以捕获并认为它是一个字母数字字符串。

Which of these approaches are best based on performance?基于性能,这些方法中哪一种是最好的?

You could try, remove the + if not useful:您可以尝试,如果没有用,请删除+

 /**
 * Assuming that a phone number is of an international format, having `+` sign as prefix
 * and with no spaces in between the numbers, validates if a string is a valid phone number.
 * 
 * @param phone
 * @return resulting boolean
     */
private boolean isValidPhoneNumber(String phone) {
    if(phone == null) return false;
    
    return Pattern.matches("\\+\\d{11,15}", phone);
}

I am checking from i=1 as 1st character will be '+' for country code.我正在检查 i=1 作为国家代码的第一个字符将是“+”。

You can use the regex, \\+\\d{n - 1} which means the first character is + and the remaining n - 1 characters are digits.您可以使用正则表达式\\+\\d{n - 1}这意味着第一个字符是+ ,其余n - 1字符是数字。 It also means that the total length of the string should be n .这也意味着字符串的总长度应该是n

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(containsOnlyDigits("+123456789", 10));
        System.out.println(containsOnlyDigits("+123456789", 9));
        System.out.println(containsOnlyDigits("+123456789", 8));
        System.out.println(containsOnlyDigits("-123456789", 9));
        System.out.println(containsOnlyDigits("123456789", 9));
        System.out.println(containsOnlyDigits("ABC123456", 9));
    }

    public static boolean containsOnlyDigits(String str, int n) {
        String regex = "\\+\\d{" + (n - 1) + "}";
        return str.matches(regex);
    }
}

Output:输出:

true
false
false
false
false
false

Using regular expressions is costly.使用正则表达式代价高昂。 For this reason, you can easily solve this problem using the lambda notation in Java 8.因此,您可以使用 Java 8 中的 lambda 表示法轻松解决此问题。

boolean numericControl = str.chars().allMatch(x -> Character.isDigit(x));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM