Consider taking advantage of existing features that could provide an additional layer of validation.
mainly System.Net.Mail.MailAddress
Also as mentioned in a comment, no need to be creating the regular expression every time the function is called.
static Regex mailExpression = new Regex(@"(.+?(?=<))<(.*@.*?)>");
private static MailAddress getAddress(string address) {
if (address == null) throw new ArgumentNullException("address");
if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");
var plainaddress = address.Trim();
var groups = mailExpression.Match(plainaddress).Groups;
return groups.Count == 1
? new MailAddress(plainaddress)
: new MailAddress(groups[2].Value.Trim(), groups[1].Value.Trim());
}
According to reference source code, internally MailAddress
will try to parse the address given to it.
This avoids having to roll your own parser as one already exists out of the box that has been tried, tested and is stable.
private static MailAddress getAddress(string address) {
if (address == null) throw new ArgumentNullException("address");
if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");
address = address.Trim();
return new MailAddress(address);
}
You have the added advantage of having a strongly typed object model to work with that will provide you with usable properties.
The following Unit Test demonstrates the desired behavior.
[TestClass]
public class EmailParserTest {
[TestMethod]
public void Should_Parse_EmailAddress_With_Alias() {
//Arrange
var expectedAlias = "test my address";
var expectedAddress = "[email protected]";
string addressWithAlias = "test my address <[email protected]>";
//Act
var mailAddressWithAlias = getAddress(addressWithAlias);
//Assert
mailAddressWithAlias
.Should()
.NotBeNull()
.And.Match<MailAddress>(_ => _.Address == expectedAddress && _.DisplayName == expectedAlias);
}
[TestMethod]
public void Should_Parse_EmailAddress_Without_Alias() {
//Arrange
var addressWithoutAlias = "[email protected]";
//Act
var mailAddressWithoutAlias = getAddress(addressWithoutAlias);
//Assert
mailAddressWithoutAlias
.Should()
.NotBeNull()
.And.Match<MailAddress>(_ => _.Address == addressWithoutAlias && _.DisplayName == string.Empty);
;
}
private static MailAddress getAddress(string address) {
if (address == null) throw new ArgumentNullException("address");
if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");
address = address.Trim();
return new MailAddress(address);
}
}
James Bond <[email protected]>
will display in outlook justJames Bond
instead of his e-mail-address. So, this is kind of a standard :) \$\endgroup\$