我在字符串中有一些字符。我想从这个字符串中找到所有电子邮件地址并找到索引。
mytext= "My mail id is grk@gmail.com and my friend mail id is newxyz@yahoo.com";
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$ ");
Match match = regex.Match(mytext);
if (match.Success) {
TextBox1.Text = match.Value;
int IndexValue=match.Index;
}
match = match.NextMatch();
if (match.Success) {
TextBox2.Text = match.Value;
int IndexValue=match.Index;
}
答案 0 :(得分:1)
这有效......
var mytext = "My mail id is grk@gmail.com and my friend mail id is newxyz@yahoo.com";
Regex regex = new Regex(@"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])");
Match match = regex.Match(mytext);
if (match.Success)
{
TextBox1.Text = match.Value;
int IndexValue = match.Index;
}
match = match.NextMatch();
if (match.Success)
{
TextBox2.Text = match.Value;
int IndexValue = match.Index;
}
有关详细信息,请参阅http://emailregex.com/。
答案 1 :(得分:0)
尝试以下代码段。正则表达式from
void Main()
{
string pattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
string input = @"My mail id is grk@gmail.com and my friend mail id is newxyz@yahoo.com";
var m = Regex.Match(input, pattern);
if (m.Success)
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
m = m.NextMatch();
if (m.Success)
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
// Define other methods and classes here