2014-05-25 188 views
-1

古怪的人,但:如果字符串包含一個字母,返回整個字符串

讓你想回到我們說你一個巨大的HTML頁面,如果網頁中包含電子郵件地址(尋找一個@符號)該電子郵件。

到目前爲止,我知道我需要的東西是這樣的:

String email; 

if (myString.contains("@")) { 

     email = myString.substring("@") 
} 

我知道怎麼去了@但我怎麼回去字符串中找到前等什麼?

+1

使用正則表達式可能會更好嗎? – elbaulp

+7

@ algui91如果你用正則表達式解析HTML,你將被普魯士馬踢進你的屁股。我保證。 –

+5

我不會使用純String方法或正則表達式從HTML頁面讀取數據。有專門的網頁爬行和HTML解析工具。關閉我的頭頂,看看[jsoup](http://jsoup.org/) – toniedzwiedz

回答

0

如果myString是你從此HTML頁面收到email字符串,

可以返回相同的字符串,如果有正確的@。像下面的東西

String email; 

if (myString.contains("@")) { 

     email = myString; 
} 

什麼是挑戰在這裏..你能解釋任何挑戰嗎?

+0

對不起,myString實際上是整個HTML頁面 – user3504452

+0

爲什麼不能發送HTML頁面到服務器的請求參數?這使得您的生活易於獲得電子郵件作爲一個單獨的請求參數,你可以很容易地驗證它...在那裏的任何挑戰? –

0
String email; 

if (myString.contains("@")) { 
    // Locate the @ 
    int atLocation = myString.indexOf("@"); 
    // Get the string before the @ 
    String start = myString.substring(0, atLocation); 
    // Substring from the last space before the end 
    start = start.substring(start.lastIndexOf(" "), start.length); 
    // Get the string after the @ 
    String end = myString.substring(atLocation, myString.length); 
    // Substring from the first space after the start (of the end, lol) 
    end = end.substring(end.indexOf(" "), end.length); 
    // Stick it all together 
    email = start + "@" + end; 
} 

這可能有點偏離,因爲我一直在寫javascript。 :)

+0

對不起,myString實際上是整個html頁面 – user3504452

+0

在這種情況下,我會更新我的答案。 XD電子郵件前後是否有空格? – JakeSidSmith

+0

是的,有! – user3504452

0

此方法將爲您提供一個字符串中包含的所有電子郵件地址的列表。

static ArrayList<String> getEmailAdresses(String str) { 
    ArrayList<String> result = new ArrayList<>(); 
    Matcher m = Pattern.compile("\\[email protected][^. ]+(\\.[^. ]+)*").matcher(str.replaceAll("\\s", " ")); 
    while(m.find()) { 
     result.add(m.group()); 
    } 
    return result; 
} 
0

而不是確切的代碼,我想給你一個方法。

只用@符號檢查可能不太合適,因爲在其他情況下也可能是合適的。

通過互聯網搜索或創建自己的,與電子郵件相匹配的正則表達式模式。 (如果你願意,你可以添加對電子郵件服務提供商的檢查以及)這裏是一個鏈接](http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

Get the index of a pattern in a string using regex,並找出子(電子郵件你的情況)。

相關問題