簡體   English   中英

當字符串長度變化時使用 String.format()

[英]Using String.format() when a string length varies

String的長度不可預測時,如何使用String.format() 我正在制作一個需要電子郵件的程序,“@”的位置會根據它之前的長度而有所不同。

編輯:我的意思是,我需要檢查電子郵件格式是否有效。 示例:johndoe@johndoe.usa 是一個有效的電子郵件,但執行 johndoejohndoe,usa 是無效的。 所以我需要弄清楚是否

  1. 格式有效
  2. String長度因電子郵件而異時,找出如何使用String.format()查看格式是否有效。

我不完全確定你認為什么是有效的電子郵件,但我基於這個假設做了以下事情:

有效的電子郵件是包含至少 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.

根據您對有效電子郵件的定義,您可以相應地調整模式 我希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM