在字符串中查找字符值并创建子字符串

时间:2013-05-31 23:13:15

标签: c# string substring arrays

在我看来这是一个常见的场景

字符串类似于:

"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"

我的代码现在试图从“@”的索引中计算 Down 因此,在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 个答案:

答案 0 :(得分: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('@')));
}

Demo

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

答案 1 :(得分: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/

找到一个

答案 2 :(得分:0)

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

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

这将打破多个电子邮件的字符串,但对此的修复应该是微不足道的。