当字符串长度变化时使用String.format()

时间:2015-06-28 07:24:25

标签: java string format

String.format()的长度无法预测时,如何使用String?我正在制作一个需要电子邮件的程序以及" @"将根据前面的长度而有所不同。

编辑:我的意思是,我需要检查电子邮件格式是否有效。示例:johndoe@johndoe.usa是一封有效的电子邮件,但在执行johndoejohndoe时,美国并不有效。所以我需要弄清楚是否

  1. 格式有效
  2. String.format()长度因电子邮件而异时,了解如何查看格式是否对String有效。

1 个答案:

答案 0 :(得分:1)

我不完全确定你认为什么是有效的电子邮件,但我基于这个假设做了以下事情:

  

有效的电子邮件是至少包含1个字符的字符串,   接着是'@'符号,后跟至少1   字母表,后面跟着'。'性格,并以。结尾   至少1个字母

以下是使用正则表达式的代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QuickTester {

    private static String[] emails = {"abc@gmail.com",
            "randomStringThatMakesNoSense",
            "abc@@@@@", "thisIsRegex@rubbish",
            "test123.com", "goodEmail@hotmail.com",
            "@asdasd@gg.com"};

    public static void main(String[] args) {

        for(String email : emails) {
        System.out.printf("%s is %s.%n",
                email, 
                (isValidEmail(email) ? "Valid" : "Not Valid"));
        }   
    }

    // Assumes that domain name does not contain digits
    private static boolean isValidEmail (String emailStr) {

        // Looking for a string that has at least 1 word character,
        // followed by the '@' sign, followed by at least 1
        // alphabet, followed by the '.' character, and ending with
        // at least 1 alphabet
        String emailPattern = 
                "^\\w{1,}@[a-zA-Z]{1,}\\.[a-zA-Z]{1,}$";

        Matcher m = Pattern.compile(emailPattern).matcher(emailStr);
        return m.matches();
    }
}

<强>输出:

abc@gmail.com is Valid.
randomStringThatMakesNoSense is Not Valid.
abc@@@@@ is Not Valid.
thisIsRegex@rubbish is Not Valid.
test123.com is Not Valid.
goodEmail@hotmail.com is Valid.
@asdasd@gg.com is Not Valid.

根据您对有效电子邮件的定义,您可以相应地调整Pattern。我希望这有帮助!