2011-05-28 65 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