2013-10-03 13 views
0

首先,對於可能發生的任何拼寫/語法錯誤感到抱歉。我試圖得到一些複雜的正則表達式問題解決,但我似乎無法弄清楚如何。我試圖過濾掉某些字符串的某些部分。然而,這工作!有一行是可選的,第二個是電子郵件。我怎麼能告訴正則表達式這部分是可選的,只應該搜索它是否存在於字符串中。正則表達式,僅當它存在於當前字符串中時才匹配

字符串

  • [註釋]喵[/127.0.0.1]
  • [註釋]暗影[/127.0.0.1]
  • [註釋] [電子郵件]狡猾[/127.0。 0.1]
  • [評論] [EMAIL2] PerfectAim [/127.0.0.1]

我已經試過

Regex regexUserCommented = new Regex(
    @"(\[COMMENT\])\ " + // COMMENT 
    @"(\[.*\]) " +  // Email, this needs to be optional but how?! 
    @"(\w(?<!\d)[\w'-]*)" // User 
); 

if (regexUserCommented.IsMatch(test)) 
{ 
    var infoMatches = regexUserCommented.Split(test); 
    Console.WriteLine(infoMatches[3]); // User 
} 

任何人有任何想法如何讓電子郵件部分可選? (在正則表達式中是可選的,所以如果它不在字符串中,它不會做任何事情,它只是跳過電子郵件部分,抱歉我的英語不好> :)。

+1

你可能需要一個['?'量詞(http://msdn.microsoft.com/en-us/library/az24scfc.aspx#quantifiers)(匹配零次或一次)。例如,'(\ [。* \])?'。 – rutter

+0

你有沒有試過@「((\ [。* \]))?」 –

+0

@rutter這似乎工作atm :),但我怎麼能從'var infoMatches = regexUserCommented.Split(test);'?的結果中排除它?對不起所有問題> :. –

回答

0

使用組...

Regex regexUserCommented = new Regex(
    @"(\[COMMENT\])\ " + // COMMENT 
    @"((\[.*\]))?" +  // Email, this needs to be optional but how?! 
    @"(\w(?<!\d)[\w'-]*)" // User 
); 

var match = regexUserCommented.Match(test); 

if (match.Groups.Count == 5) 
{ 
    Console.WriteLine("==> {0}", match.Groups[4].Value); 
} 
else 
{ 
    Console.WriteLine("==> Not matched"); 
} 
+0

是的,抱歉沒有發佈答案,不得不去工作等我接受你的答案,因爲它解決了問題:)。 –

相關問題