2012-08-06 18 views
0

我有這樣的內容:

var testInput = 
    "05(testcontent)\r\n" + 
    "06(testcontent2)\r\n" + 
    "07(testcontent3)(testcontent4)" + 
    "08(testcontent5)"; 

我需要每行的一個代碼串和兩個值的字符串。 對於第一行:

  • 代碼:"05"
  • 值1:"testcontent"
  • 值2:空字符串。

對於第三行:

  • 代碼:"07"
  • 值1:"testcontent3"
  • 值2:"testcontent4"

我使用的圖案:

// (?<Code>[0-9]{2}) - 2 digit number 
// \((?<Value1>.+)\) - First value, which is inside the parentheses. 
// (\((?<Value2>.+)\))? - Second value, which also is inside the parentheses. 
// The second value does not always exist. Which is why it has "?" at its end. 
var testPattern = @"(?<Code>[0-9]{2})\((?<Value1>.+)\)(\((?<Value2>.+)\))?"; 

的代碼我使用:

var testRegex = new Regex(testPattern, 
    RegexOptions.Compiled | 
    RegexOptions.CultureInvariant | 
    RegexOptions.ExplicitCapture | 
    RegexOptions.Multiline); 
foreach (Match match in testRegex.Matches(testInput)) 
    Console.WriteLine("{0}: {1} | {2}", 
     match.Groups["Code"].Value, 
     match.Groups["Value1"].Value, 
     match.Groups["Value2"].Value); 

結果我得到:

05: testcontent | 
06: testcontent2 | 
07: testcontent3)(testcontent4)08(testcontent5 | 

如果我在的模式結束的開始和$使用^,我得到更糟:

07: testcontent3)(testcontent4)08(testcontent5 | 

所以,

  • 爲什麼當我指定「RegexOptions.Multiline」時,^$會更復雜?
  • 我的模式有什麼問題?

回答

1

你會在你的Value1或Value2中關閉圓括號嗎?如果不是,我會建議使用否定字符類,如[^)]+而不是.+。原因是.+是「貪婪」(即重複儘可能多次)在這種情況下引起問題。

+0

工作就像一個魅力,謝謝。 – 2012-08-06 08:34:09

+0

快速提問:'[^)] +'意味着「至少一個不是')'的字符」。我如何指定「至少一個不是'('或')'」的字符? – 2012-08-06 09:23:22

+1

您可以在否定字符類中添加所需的所有字符,例如'[^()]'。這意味着「只有一個字符不是'('或')'」。在此之後添加'+'即可得到「至少一個字符」。 – mkataja 2012-08-06 10:18:30