我不完全知道你會認爲作爲一個有效的電子郵件,但我做了以下基於這樣的假設:
一個有效的電子郵件是具有至少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。我希望這有幫助!
請包括一些示例(您想格式化的電子郵件)和預期結果? – Gosu
解決方法是解析字符串並手動查找'@'分隔符。這可以通過遍歷每個字符的for循環完成。 – Boris
String.format(..)不使用「@」標記,但使用特殊的格式說明符,例如字符串的「%s」或數字的「%d」。請參閱http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax。這些值出現在字符串中的位置並不重要。它們將插入相應說明符的位置。 – redge