2013-03-14 192 views
0

好吧,所以我想創建一個簡單的電子郵件驗證應用程序。找到另一個字符串內的多個字符串

我被困在一個特定位上,我需要在1個字符串中找到2個字符串。我想知道電子​​郵件中是否有.com或.co.uk。到目前爲止,我只是爲了檢查.com。我到處尋找,找不到解決方案。我曾嘗試做.indexof(dotCom && dotUK),但沒有奏效。

所以只需要這麼說「.COM」或「.co.uk」

 String dotCom = ".com"; 
    String dotUK = ".co.uk"; 

    rest = user_email.indexOf(dotCom); 

    if (rest== -1){ 
     System.out.println("Invalid email address. Must contain .com or .co.uk"); 
    }else{ 
     System.out.println("Valid email address"); 
    } 
+0

你有沒有想過使用正則表達式匹配一個有效的電子郵件模式? – StepTNT 2013-03-14 23:06:40

+0

如果他只從兩個域擴展,則regex會很有用。對於這種情況(只有兩個域),正則表達式會使問題更加複雜。 – 2013-03-14 23:09:17

回答

2
if(mail.contains(".com") || mail.contains(".co.uk")) { 
    //is valid 
} 

不檢查字符串的所有腦幹等字符串中使用indexOf,如果你不關心它的實際指數。

如果你只是想知道,如果一些字符串包含另一個字符串,用contains方法 - 這是更直接的

的建議,更好的方式是:

if(mail.endsWith(".com") || mail.endsWith(".co.uk")) { 
    //is valid 
} 
+1

假設這些電子郵件是有效的,他們將永遠以這些結束,所以我會建議endsWith而不是包含 – 2013-03-14 23:13:06

+0

@SeanF,好點 – dantuch 2013-03-14 23:14:06

+0

我試着包含您建議的代碼,並得到錯誤「int不能被解除引用」:s – user2131803 2013-03-14 23:18:15

0

好,使工作中的片段中,這將是

if (user_email.indexOf(dotCom) == -1 && user_email.indexOf(dotUK) == -1){ 
System.out.println("Invalid email address. Must contain .com or .co.uk"); 

} 
    else { 
    System.out.println("Valid email address"); 
} 

,另一方面,你可以嘗試Regular expressions一個更靈活的解決方案。 希望它有助於

1

你可以使用正則表達式,或後綴的這樣一個集合:

private static boolean matches(final String  mail, 
           final String ... suffixes) 
{ 
    String match; 

    match = null; 

    for(final String suffix : suffixes) 
    { 
     if(mail.endsWith(suffix)) 
     { 
      match = suffix; 
      break; 
     } 
    } 

    // or return (match); if you want to know the type. 
    return (match != null); 
} 
相關問題