Reputation: 701
I have a textBox control that lets the user their email address/addresses. The use may enter email by supplying comma or in next line (new line).
The task is to check whether the textBox contains new line (\n) character or commas then split the email addresses accordingly.
I applied:
string[] emails = txtemailAddress.Text.Split('\n');
it splits the email addresses.
I need a single routine that should check whether the textBox contains ",' {or} '\n' and
split the string based on the split character.If the email address is invalid in format it should throw exception as well.
Thanks in advance.
Upvotes: 0
Views: 382
Reputation: 11079
To split use
string[] emails = txtemailAddress.Text.Split('\n', ',');
this method is faster than regular expressions
To validate email see these questions:
https://stackoverflow.com/search?q=validate+email
this is too complicated task to open another discussion here.
Upvotes: 0
Reputation: 158181
Other answers are good, but since you asked about regular expression: \s*,\s*|\s+
should work, I believe. It splits between commas (with any amount of whitespace before or after it) and any form of whitespace (newline, space, tab, etc.).
var addresses = Regex.Split(text, @"\s*,\s*|\s+");
Upvotes: 0
Reputation: 23044
it's not easy to write a parser to check if email is correct or not. for splitting you can pass array of chars to split by using it like
char[] delimiters = new char[] { ',', '\n' };
string[] emails = txtemailAddress.Text.Split(delimiters );
Upvotes: 0
Reputation: 158349
The string.Split method accepts an array of characters to split on:
// split on newline or comma
txtemailAddress.Text.Split(new[]{'\n', ','});
Regarding validating email addresses, this is one of those tasks that may seem simple at first glance, but that proves to be more of a challange than expected. This has been dicussed here at SO before.
Upvotes: 1