Nick Strupat
Nick Strupat

Reputation: 5063

How do I do this with one regular expression pattern instead of three?

I think I need to use an alternation construct but I can't get it to work. How can I get this logic into one regular expression pattern?

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");

EDIT:

Some sample cases should help with your questions

From: email

and

From: name(email)

Those are the two possible cases. I'm looking to match them so I can do

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

Suggestions for a different approach are welcome! Thanks!

Upvotes: 1

Views: 99

Answers (1)

agent-j
agent-j

Reputation: 27913

This is literally what you're asking for: "(?=" + regex1 + ")" + regex2 + "|" + regex3

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

But I don't think that's really what you want.

With .net's Regex, you can name groups like this: (?<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);

However, your \r\n is probably not right. That would be a literal rnFrom:. Try this instead.

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

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

Upvotes: 3

Related Questions