How to split E-mail address from a text?
In a text box, I keep E-mail addresses. for example
Text_box.value="a@hotmail.com,b@hotmail.com,c@hotmail.com"
How can I split all of the email addresses? Should I use Regex开发者_如何学JAVA?
Finally, I want to keep any E-mail address which is correctly coded by user
string[] s=Text_box.Text.split(',');
Regex R=new Regex("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b");
var temp=from t in s where R.IsMatch(t) select t;
List<string> final=new List<string>();
final.addrange(temp);
use this
string[] emails = list.Split(new char[]{','});
This will only print the matched email address and not which does not match.
private void Match()
{
Regex validationExpression = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
string text = "whatever@gmail;a@hotmail.com,gmail@sync,b@hotmail.com,c@hotmail.com,what,dhinesh@c";
MatchCollection matchCollection = validationExpression.Matches(text);
foreach (var matchedEmailAddress in matchCollection)
{
Console.WriteLine(matchedEmailAddress.ToString());
}
Console.ReadLine();
}
This will print
a@hotmail.com
b@hotmail.com
c@hotmail.com
Other things will not be matched by regular expression.
"a@hotmail.com,b@hotmail.com,c@hotmail.com".Split(',');
There are two ways to split string.
1) Every string type object has method called Split() which takes array of characters or array of strings. Elements of this array are used to split given string.
string[] parts = Text_box.value.Split(new char[] {','});
2) Although string.Split() is enough in this example, we can achieve same result using regular expressions. Regex to split is :
string[] parts = Regex.Split(Text_box.value,@",");
You have to use correct regexp to find all forms of email adresses (with latin letters). Check on wikipedia ( http://en.wikipedia.org/wiki/Email_address ) for correct syntax of email address (easier way) or in RFC5322, 5321 (much harder to understand).
I'm using this:
(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-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-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
精彩评论