【问题标题】:Extract number values enclosed inside curly brackets提取大括号内的数值
【发布时间】:2011-05-28 16:53:20
【问题描述】:

我想从给定文件中提取一些字符串数据。文件得到的结构如:


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


我想提取下一个值:

  • 姓名;
  • 猫;
  • yvcvt 标签后面的数字;

我使用了下一个正则表达式:

  • @"(?<name>\w+), (?<cat>\w+)" 用于提取前两项;
  • @"(?:\{y:(?<y>\d+), +v:(?<v>\d+), +c:(?<c>\d+), +vt:(?<vt>\d+)\}, ?)+" 用于提取大括号中的其他值。

我将这两者连接起来并在正则表达式测试器中进行了测试。但正如预期的那样,我只得到一组提取的数字。我需要另一部分的结果({y:2007, v:1000, c:100, vt:1})。此外,可能有两个以上的部分。

如何修复我的正则表达式?然后我如何收集相应部分的所有数字集。

【问题讨论】:

    标签: c# regex capture regex-group


    【解决方案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);
        }
    }
    

    【讨论】:

    • 好的!如何获取提取的组?
    • @helicera,我刚刚添加了用法示例:)
    猜你喜欢
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 2016-09-17
    • 1970-01-01
    • 2019-05-14
    相关资源
    最近更新 更多