2013-05-31 37 views
0

這是一個常見的場景找到字符的字符串值,並創建一個子在我看來

字符串是一樣的東西:

"this is my story, if it's interesting [email protected] so thanks for your time" 

我需要使它的財產以後像

"this is my story, if it's interesting so thanks for your time" 
"[email protected]" 

我現在的代碼試圖從「@」 的索引中計數向下,因此它在iter內檢查的次數更少for循環

 public string formatResultContentAndEmail(string source) 
     { 
      char[] Str2CahrArr = source.ToCharArray(); 
      var trgt = source.IndexOf('@'); 
      var stepsBack=0; 
      for (int i = trgt; i >0; i--) 
      { 
       var test = Str2CahrArr[i]; 
       if (Str2CahrArr[i].Equals(" ")) 
       { 
        stepsBack = i; break; 
       } 
      } 

      return "";//<======change this when done tests 
     } 

我的第一個問題是,當我試圖找到空間時找不到它。

但即使我會解決這個問題,這種方法是正確的嗎?

提取該完整段落的郵件子字符串的最簡單方法是什麼?

回答

3

也許有更好的正則表達式的方法,其搜索真正的電子郵件,這是可讀的,高效:

string text = "this is my story, if it's interesting [email protected] so thanks for your time"; 
if(text.Contains('@')) 
{ 
    string[] words = text.Split(); 
    string[] emails = words.Where(word => word.Contains('@')).ToArray(); 
    text = string.Join(" ", words.Where(word => !word.Contains('@'))); 
} 

Demo

this is my story, if it's interesting so thanks for your time 
[email protected] 
+0

是的,肯定看起來比其他正則表達式更人性化,我想在我的情況下是最好用的。感謝思考簡單..如果它是(: – LoneXcoder

+0

,如果我可以,我會給你另一個+1新的(至少對我來說)在線IDE基準測試/測試環境 – LoneXcoder

0

我的建議如下所示,使用String.split()

public String getMail(String inp) { 
    String[] prts = inp.split(" "); 
    for(String tmp : prts) { 
    if(tmp.contains("@")) { 
     return tmp; 
    } 
    } 
} 

這將上串斷開與多個電子郵件,但是對於修復應該是微不足道的。

1
public string[] ExtractEmails(string str) 
{ 
    string RegexPattern = @"\b[A-Z0-9._-][email protected][A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}\b"; 

    // Find matches 
    System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(str, RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); 

    string[] MatchList = new string[matches.Count]; 

    // add each match 
    foreach (System.Text.RegularExpressions.Match match in matches) 
     MatchList[c] = match.ToString(); 

    return MatchList; 
} 

來源:http://coderbuddy.wordpress.com/2009/10/31/coder-buddyc-code-to-extract-email/

如果你需要一個更好的正則表達式模式,你也許可以找到一個在http://www.regular-expressions.info/

+0

擊敗我吧。正則表達式是最好的方法。 –

+0

我想我會在正則表達式中更好地處理正則表達式,但現在我將首先測試@Tim方法。謝謝,我肯定會在稍後看到,但! – LoneXcoder

相關問題