如何使用一个正则表达式而不是三个?

时间:2011-07-04 18:54:51

标签: c# regex

我想我需要使用一个替代构造,但我不能让它工作。如何将此逻辑转换为一个正则表达式模式?

match = Regex.Match(message2.Body, @"\r\nFrom: .+\(.+\)\r\n");
if (match.Success)
    match = Regex.Match(message2.Body, @"\r\nFrom: (.+)\((.+)\)\r\n");
else
    match = Regex.Match(message2.Body, @"\r\nFrom: ()(.+)\r\n");

编辑:

一些示例案例应该有助于解决您的问题

From: email

From: name(email)

这是两种可能的情况。我想匹配它们,所以我可以做到

string name = match.Groups[1].Value;
string email = match.Groups[2].Value;

欢迎提出不同方法的建议! 谢谢!

1 个答案:

答案 0 :(得分:3)

这就是你要求的:"(?=" + regex1 + ")" + regex2 + "|" + regex3

match = Regex.Match(message.Body, @"(?=\r\nFrom: (.+\(.+\))\r\n)\r\nFrom: (.+)\((.+)\)\r\n|\r\nFrom: ()(.+)\r\n");

但我认为这不是你想要的。

使用.net的Regex,您可以命名这样的组:(?<name>regex)

match = Regex.Match(message.Body, @"\r\nFrom: (?<one>.+)\((?<two>.+)\)\r\n|\r\nFrom: (?<one>)(?<two>.+)\r\n");

Console.WriteLine (match.Groups["one"].Value);
Console.WriteLine (match.Groups["two"].Value);

但是,您的\r\n可能不对。这将是文字rnFrom:。试试这个。

match = Regex.Match(message.Body, @"^From: (?:(?<one>.+)\((?<two>.+)\)|(?<one>)(?<two>.+))$");

Console.WriteLine (match.Groups["one"].Value);
Console.WriteLine (match.Groups["two"].Value);
相关问题