捕获计数始终为零

本文关键字: | 更新日期: 2023-09-27 17:57:57

我遇到了一个问题。我使用以下正则表达式:


Pattern =
  (?'name''w+(?:'w|'s)*), 's*
  (?'category''w+(?:'w|'s)*), 's*
  (?:
      '{ 's*
          [yY]: (?'year''d+), 's*
          [vV]: (?'volume'(?:([1-9][0-9]*'.?[0-9]*)|('.[0-9]+))+), 's*
      '} 's*
      ,? 's*
  )*

具有CCD_ 1选项。在我调试它之前,我的应用程序中的一切似乎都很好;遇到问题。


var Year = default(UInt32);
// ...
if((Match = Regex.Match(Line, Pattern, Options)).Success)
{
    // Getting Product header information
    Name = Match.Groups["name"].Value;
    // Gathering Product statistics
    for(var ix = default(Int32); ix < Match.Groups["year"].Captures.Count; ix++)
    {
       // never get here
       Year = UInt32.Parse(Match.Groups["year"].Captures[ix].Value, NumberType, Culture);
    }
}

所以在上面的代码中。。就我而言,Match总是成功的。我得到了Name的正确值,但当轮到for时,程序流只是忽略了它。我调试了Match.Groups["year"]中没有Captures。所以这是合乎逻辑的行为。但对我来说,我错在哪里并不明显。帮助

前面有一个连接的帖子提取了我制作的花括号内的数值。

谢谢!

编辑。输入样本

Sherwood, reciever, {y:2008,V:5528.35}, {y:2009,V:8653.89}, {y:2010, V:4290.51}
  • 我需要捕获20085528.3520098653.89IgnorePatternWhitespaces0、4290.51值,并将它们作为命名组进行操作

二维编辑

我尝试使用ExplicitCapture选项和以下表达式:

(?<name>'w+(w'| )*), (?<category>'w+(w'| )*), ('{[yY]:(?<year>'d+), *[vV]:(?<volume>(([1-9][0-9]*'.?[0-9]*)|('.[0-9]+))+)'}(, )?)+

但这无济于事。

捕获计数始终为零

编辑:您可以通过匹配所有内容来简化,直到下一个逗号:[^,]*。这里有一个完整的代码片段来匹配您的源数据:

var testRegex = new Regex(@"
    (?'name'[^,]*),'s*
    (?'category'[^,]*),'s*
    ({y:(?'year'[^,]*),'s*
    V:(?'volume'[^,]*),?'s*)*",
    RegexOptions.IgnorePatternWhitespace);
var testMatches = testRegex.Matches(
    "Sherwood, reciev, {y:2008,V:5528.35}, {y:2009,V:8653.89}, {y:2010, V:4290.51}");
foreach (Match testMatch in testMatches)
{
    Console.WriteLine("Name = {0}", testMatch.Groups["name"].Value);
    foreach (var capture in testMatch.Groups["year"].Captures)
        Console.WriteLine("    Year = {0}", capture);
}

此打印:

Name = Sherwood
    Year = 2008
    Year = 2009
    Year = 2010

我认为问题是逗号:

, 's* '}

哪个应该是可选的(或省略?):

,? 's* '}

阐述MRAB所说的:

(?'name'
    'w+
    (?:
       'w|'s
    )*
),
's* 
(?'category'
     'w+
     (?:
         'w|'s
     )*
),
's* 
(?:
      '{ 
          's*
          [yY]:
          (?'year'
               'd+
          ),
          's*
          [vV]:
          (?'volume'
               (?:
                   (     # Why do you need capturing parenth's here ?
                     [1-9][0-9]*
                     '.?
                     [0-9]*
                   )
                 |
                   (
                     '.[0-9]+
                   )
               )+
          ),        # I'm just guessing this comma doesent match input samples
          's*
      '}
      's*
      ,?
      's*
)*

Sherwood, reciever, {y:2008,V:5528.35}, {y:2009,V:8653.89}, {y:2010, V:4290.51}
相关文章:
  • 没有找到相关文章