0

在我看来,这是一个常见的情况

字符串类似于:

"this is my story, if it's interesting somemail@domain.com so thanks for your time"

我需要让它像

"this is my story, if it's interesting  so thanks for your time"
"somemail@domain.com"

我现在的代码正在尝试从“@”的索引倒数因此在 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
        }

我在那次尝试中的第一个问题是当它撞到空格时我找不到。

但即使我会解决这个问题,这种方法是否正确?

提取该完整段落的邮件子字符串的最简单方法是什么?

4

3 回答 3

3

也许有一种更好的正则表达式方法可以搜索真实的电子邮件,这是可读且有效的:

string text = "this is my story, if it's interesting somemail@domain.com 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('@')));
}

演示

this is my story, if it's interesting so thanks for your time
somemail@domain.com
于 2013-05-31T23:22:54.830 回答
1
public string[] ExtractEmails(string str)
{
    string RegexPattern = @"\b[A-Z0-9._-]+@[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/找到一个

于 2013-05-31T23:22:36.343 回答
0

我的建议如下,使用 String.split()

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

这将破坏包含不止一封电子邮件的字符串,但对此的修复应该是微不足道的。

于 2013-05-31T23:21:01.683 回答