2015-06-28 30 views
2

String的長度不可預知時,如何使用String.format()?我正在製作一個需要電子郵件的程序,而「@」的位置會根據它之前的長度而有所不同。字符串長度變化時使用String.format()

編輯:我的意思是,我需要檢查電子郵件格式是否有效。例如:[email protected]是一個有效的電子郵件,但是做johndoejohndoe,美國是無效的。所以,我需要找出是否

  1. 格式是有效
  2. 找出如何看的格式是有效的與String.format()String長度將取決於電子郵件有所不同。
+6

請包括一些示例(您想格式化的電子郵件)和預期結果? – Gosu

+0

解決方法是解析字符串並手動查找'@'分隔符。這可以通過遍歷每個字符的for循環完成。 – Boris

+0

String.format(..)不使用「@」標記,但使用特殊的格式說明符,例如字符串的「%s」或數字的「%d」。請參閱http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax。這些值出現在字符串中的位置並不重要。它們將插入相應說明符的位置。 – redge

回答

1

我不完全知道你會認爲作爲一個有效的電子郵件,但我做了以下基於這樣的假設:

一個有效的電子郵件是具有至少1個字字符的字符串, 後面加'@'符號,後面至少有1個 字母,後面跟着'。'。性格,並與 至少1字母

這裏結束是一個使用正則表達式的代碼:

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

public class QuickTester { 

    private static String[] emails = {"[email protected]", 
      "randomStringThatMakesNoSense", 
      "[email protected]@@@@", "[email protected]", 
      "test123.com", "[email protected]", 
      "@[email protected]"}; 

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

輸出:根據您的有效電子郵件的定義

[email protected] is Valid. 
randomStringThatMakesNoSense is Not Valid. 
[email protected]@@@@ is Not Valid. 
[email protected] is Not Valid. 
test123.com is Not Valid. 
[email protected] is Valid. 
@[email protected] is Not Valid. 

,您可以相應地調整Pattern。我希望這有幫助!

+0

是的,這是我的意思,謝謝!對不起,我可以把事情說得很複雜。 –