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

Using String.format() when a string length varies

String 的长度不可预测时,如何使用 String.format()?我正在制作一个需要电子邮件的程序,“@”的位置会根据它前面的长度而有所不同。

编辑:我的意思是,我需要检查电子邮件格式是否有效。示例:johndoe@johndoe.usa 是一个有效的电子邮件,但是做 johndoejohndoe,usa 是无效的。所以我需要弄清楚

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

我不完全确定您认为什么是有效电子邮件,但我基于此假设做了以下操作:

A valid email is 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

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

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。希望对您有所帮助!