2011-07-04 2 views
1

나는 alternation 구조를 사용해야한다고 생각하지만 작동시키지 못한다. 어떻게이 논리를 하나의 정규식 패턴으로 만들 수 있습니까?3 대신 하나의 정규식 패턴을 사용하면 어떻게됩니까?

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; 

다른 접근 방식을 제안합니다. 환영합니다! 감사합니다. "(?=" + regex1 + ")" + regex2 + "|" + regex3

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

그러나 나는 당신이 원하는 정말 생각하지 않습니다 :

+0

표현식으로 무엇을 달성하고 싶습니까? 특히 세 번째 것은'')''에 좋은 것인가? – stema

+0

경기를 어떻게 계획 하시겠습니까? 아마도 첫번째 그룹과 두번째 그룹을 사용하십시오. –

답변

3

이것은 당신이 요구하는지 그대로입니다.

.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); 
관련 문제