使用c#从文本中提取所有电子邮件地址 [英] extract all email address from a text using c#
本文介绍了使用c#从文本中提取所有电子邮件地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如
我的电子邮件地址是mrrame@gmail.com,他的电子邮件是mrgar@yahoo.com
应该返回
mrrame@gmail.com,mrgar@yahoo.com
我尝试了以下操作,但它匹配完美的电子邮件只有。
public const string MatchEmailPattern =
@^(([\w - ] + \\)\\ [\w - ] + |([a-zA-Z] {1} | [\w - ] {2,}))@
+ @((([0 -1] [0-9] {1,2} |?25 [0-5] |。?2 [0-4] [0-9])\([0-1] [0-9] { 1,2} | 25 [0-5] | 2 [0-4] [0-9])\。
+ @([0-1]?[0-9] {1, 2} | 25 [0-5] | 2 [0-4] [0-9])\([0-1] [0-9] {1,2} |。?25 [0-5] | 2 [0-4] [0-9])){1} |
+ @([a-zA-Z] + [\w - ] + \。)+ [a-zA -Z] {2,4})$;
public static bool IsEmail(string email)
{
if(email!= null)return Regex.IsMatch(email,MatchEmailPattern);
else return false;
}
解决方案
以下作品
public static void emas(string text)
{
const string MatchEmailPattern =
@(([ \w - ] + \。)+ [\w - ] + |([a-zA-Z] {1} | [\w - ] {2,}))@
+ @((([0-1] [0-9] {1,2} |?25 [0-5] | 2 [0-4] [0-9])\([0-1] ?[0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])\。
+ @([0-1]?[ 0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])\([0-1] [0-9] {1,2}。?| 25 [0-5] | 2 [0-4] [0-9])){1} |
+ @([a-zA-Z] + [\w - ] + \ 。)+ [A-ZA-Z] {2,4});
Regex rx = new Regex(MatchEmailPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);
//查找匹配。
MatchCollection matches = rx.Matches(text);
//报告找到的匹配数。
int noOfMatches = matches.Count;
//每场比赛报告
foreach(匹配匹配)
{
Console.WriteLine(match.Value.ToString());
}
}
Is there a way to extract all email addresses from a plain text using C# .
For example
my email address is mrrame@gmail.com and his email is mrgar@yahoo.com
should return
mrrame@gmail.com, mrgar@yahoo.com
I have tried the following but it matches perfect emails only.
public const string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
public static bool IsEmail(string email)
{
if (email != null) return Regex.IsMatch(email, MatchEmailPattern);
else return false;
}
解决方案
Following works
public static void emas(string text)
{
const string MatchEmailPattern =
@"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
int noOfMatches = matches.Count;
// Report on each match.
foreach (Match match in matches)
{
Console.WriteLine(match.Value.ToString());
}
}
这篇关于使用c#从文本中提取所有电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文