2011-05-28 105 views
1

我想從給定的文件中提取一些字符串數據。文件有如下結構:提取大括號內的數字值


name, catg, {y:2006, v:1000, c:100, vt:1}, {y:2007, v:1000, c:100, vt:1},.. {..}..


我想提取下一個值:

  • 名;
  • catg;
  • y,v,c,vt後的數字標籤;

我使用的下一個正則表達式:

  • @"(?<name>\w+), (?<cat>\w+)"對於前兩個項的提取;
  • @"(?:\{y:(?<y>\d+), +v:(?<v>\d+), +c:(?<c>\d+), +vt:(?<vt>\d+)\}, ?)+"用於提取大括號內的其他值。

我連接了這兩個並在正則表達式測試中做了測試。但如預期的那樣,我只得到一組提取的數字。我需要從另一部分的結果({y:2007, v:1000, c:100, vt:1})。此外,可能有兩個以上的部分。

如何修復我的正則表達式?然後,我如何從相應的部分收集所有數字集。

回答

1

這裏的固定的正則表達式(你需要指定IgnorePatternWhitespace選項):

(?'name'\w+), \s* 
(?'category'\w+), \s* 
(?: 
    \{ \s* 
     y: (?'y'\d+), \s* 
     v: (?'v'\d+), \s* 
     c: (?'c'\d+), \s* 
     vt: (?'vt'\d+) 
    \} \s* 
    ,? \s* 
)* 

而這裏的用法:

String input = @"name, catg, {y:2006, v:1000, c:100, vt:1}, {y:2007, v:1000, c:100, vt:1}"; 
String pattern = 
     @"(?'name'\w+), \s* 
     (?'category'\w+), \s* 
     (?: 
      \{ \s* 
       y: (?'y'\d+), \s* 
       v: (?'v'\d+), \s* 
       c: (?'c'\d+), \s* 
       vt: (?'vt'\d+) 
      \} \s* 
      ,? \s* 
     )* "; 
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline; 

Match match = Regex.Match(input, pattern, options); 
if (match.Success) 
{ 
    String name = match.Groups["name"].Value; 
    String category = match.Groups["category"].Value; 

    Console.WriteLine("name = {0}, category = {1}", name, category); 

    for (Int32 i = 0; i < match.Groups["y"].Captures.Count; ++i) 
    { 
     Int32 y = Int32.Parse(match.Groups["y"].Captures[i].Value); 
     Int32 v = Int32.Parse(match.Groups["v"].Captures[i].Value); 
     Int32 c = Int32.Parse(match.Groups["c"].Captures[i].Value); 
     Int32 vt = Int32.Parse(match.Groups["vt"].Captures[i].Value); 

     Console.WriteLine("y = {0}, v = {1}, c = {2}, vt = {3}", y, v, c, vt); 
    } 
} 
+0

好!我如何獲取提取的組? – lexeme 2011-05-28 17:09:34

+0

@helicera,我剛添加使用示例:) – 2011-05-28 17:10:52

+0

是的,我明白了))謝謝! – lexeme 2011-05-28 17:11:42