2012-07-30 2 views
0

아래 정규식이 문자열과 일치하면 코드가 작동합니다. 문자 중 하나가없는 경우 (예 : MONEY-STAT가 누락 된 경우)정규식 누락 문자

string s = "MONEY-ID123456:MONEY-STAT43:MONEY-PAYetr-1232832938"; 
Regex regex = 
    new Regex(@"MONEY-ID(?<moneyId>.*?)\:MONEY-STAT(?<moneyStat>.*?)\:MONEY-PAYetr-(?<moneyPaetr>.*?)$"); 
Match match = regex.Match(s); 
if (match.Success) 
{ 
    Console.WriteLine("Money ID: " + match.Groups["moneyId"].Value); 


    Console.WriteLine("Money Stat: " + match.Groups["moneyStat"].Value); 
    Console.WriteLine("Money Paetr: " + match.Groups["moneyPaetr"].Value); 

} 

Console.WriteLine("hit <enter>"); 
Console.ReadLine(); 
+0

일치하지 않습니다와'내에서 코드를 실행하지 않을 경우 (match.Success) {...}' – Qiau

+0

혼자서 시도하지 않으시겠습니까? –

+0

문자열이 작동하지 않으면 @Steve B가 작동하지 않습니다. 정규 표현식 문자열로 변경할 수있는 것은 무엇입니까? – Alvin

답변

1

나는 설명

MONEY-ID(?<moneyId>.*?)\:(?:MONEY-STAT)?(?<moneyStat>.*?)\:MONEY-PAYetr-(?<moneyPaetr>.*?)$ 

(?:MONEY-STAT)?MONEY-STAT 변경 :

(?: subexpression)  Defines a noncapturing group. 
?       Matches the previous element zero or one time. 
1

어쩌면 내가 질문을 오해 ..하지만이 소송을합니까?

(MONEY-ID(?<moneyId>.*?)\:)?(MONEY-STAT(?<moneyStat>.*?)\:)?(MONEY-PAYetr-)?(?<moneyPaetr>.*?)$ 

그것은 기본적으로 그것은 분명 어떤 종류의 분리 이후 각 토큰은 선택 .. 또한, 콜론이 포함되어 있습니다.

부인 나는 정규 표현식 .. 끔찍 해요하지만 여기 내 테스트에서 근무 : http://ideone.com/0pdFk

0

당신이 시도 할 수 :

(MONEY-ID[\d]+|(:?)MONEY-STAT[\d]+|:MONEY-PAYetr-[\d]+) 

이 아래와 같은 패턴과 일치하는 것입니다 :

머니 -ID123456 : 머니 -PAetr-1232832938

돈 STAT43 : 돈 PAYetr-1232832938

돈 ID123456 : 돈 PAYetr-1232832938 다음