0

我正在使用 C#,在其中一个地方我得到了所有人姓名的列表,他们的电子邮件 ID 格式为

name(email)\n

我刚刚想到了这个子字符串的东西。我正在寻找更优雅、更快(在访问时间、它执行的操作方面)、易于记忆的代码行来执行此操作。

string pattern =  "jackal(jackal@gmail.com)";
string email = pattern.SubString(pattern.indexOf("("),pattern.LastIndexOf(")") - pattern.indexOf("("));

//extra
string email =  pattern.Split('(',')')[1];

我认为执行上述操作将对每个字符进行顺序访问,直到找到字符的索引。现在工作正常,因为名字很短,但是当名字很大时会很困难(希望人们没有名字)

4

2 回答 2

0

A dirty hack would be to let microsoft do it for you.

try
{
    new MailAddress(input);
    //valid
}
catch (Exception ex)
{
    // invalid
}

I hope they would do a better job than a custom reg-ex.

Maintaining a custom reg-ex that takes care of everything might involve some effort.

Refer: MailAddress

Your format is actually very close to some supported formats. Text within () are treated as comments, but if you replace ( with < and ) with > and get a supported format.

于 2012-07-09T09:28:01.387 回答
0

The second parameter in Substring() is the length of the string to take, not the ending index.

Your code should read:

string pattern = "jackal(jackal@gmail.com)";

int start = pattern.IndexOf("(") + 1;
int end = pattern.LastIndexOf(")");
string email = pattern.Substring(start, end - start);

Alternatively, have a look at Regular Expression to find a string included between two characters while EXCLUDING the delimiters

于 2012-07-09T09:29:26.380 回答