list - 使用 c# 从文本字符串中查找并提取所有电子邮件地址
问题描述
有没有办法使用 C# 从纯文本中提取所有电子邮件地址。
例如这个字符串:
[id=4068;name=mrgar@yahoo.com]
[id=4078;name=mrrame@gmail.com]
应该返回
mrrame@gmail.com, mrgar@yahoo.com
我尝试了以下代码但没有成功。
拜托,你能帮帮我吗?
protected void btnFinal_Click(object sender, EventArgs e)
{
JavaScriptSerializer jsSer = new JavaScriptSerializer();
object obj = jsSer.DeserializeObject(hidJsonHolder.Value);
Movie[] listMovie = jsSer.ConvertToType<Movie[]>(obj);
foreach (Movie p in listMovie)
{
txta.Text += p.ToString();
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(p.ToString());
int noOfMatches = matches.Count;
foreach (Match match in matches)
{
Response.Write(p.ToString() + "<br />");
}
}
}
解决方案
我认为基本上你已经正确regular expression
地从文本中提取所有电子邮件地址。
但是,问题是您没有正确使用它。
正确的步骤如下:
用于regular express (Regex)
匹配文本。
对于 中的每个匹配结果MatchCollection
,从匹配结果中获取值。
为了Regular expression
更清楚,我将所有Regex
方法都放在额外的方法中,您可以单独调用这些方法来提取电子邮件。
所有代码都是根据您的原始代码编写的。
更多细节,你可以参考下面的代码。
.aspx 页面:
<form id="form1" runat="server">
<div>
<h1>This is Page</h1>
<asp:Button ID="btnFinal" runat="server" Text="Click" OnClick="btnFinal_Click" />
<br />
<asp:Label ID="displayLabel" runat="server"></asp:Label>
</div>
</form>
代码背后:
protected void btnFinal_Click(object sender, EventArgs e)
{
string exampleTxt = @"[id=4068;name=mrgar@yahoo.com][id=4078;name=mrrame@gmail.com]";
string[] emails = identifyEmailAddress(exampleTxt);
foreach (string s in emails)
{
displayLabel.Text += s + "<br />";
}
}
private string[] identifyEmailAddress(string txt)
{
const string MatchEmailPattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
MatchCollection matches = rx.Matches(txt);
int noOfMatches = matches.Count;
string[] result = new string[noOfMatches];
int i = 0;
foreach (Match match in matches)
{
result[i++] = match.Value.ToString();
}
return result;
}
推荐阅读
- vue.js - v-pagination v-model 设置为 0 而不是我设置的默认值
- ios - 如何以每秒 240 帧的速度录制和保存?
- amazon-cloudformation - 包含独立模块的应用程序的 SAM 模板
- c - C中的“ for ( ; ; ) ”是什么意思?
- c# - 在 c# 中处理另一个类的按钮逻辑问题
- html - 如何在 CSS 中创建曲线形状
- javascript - 如何在javascript中访问没有id的img元素
- laravel - 使用 Laravel Echo、laravel-echo-server 和 socket.io 广播不起作用
- sharepoint - SharePoint (2016) 列表 - 添加不要求输入的字段
- c++ - 无法自动调整 QScrollArea 的大小