1

需要帮助..为什么我得到一个 ArgumentException 是 Unhandle。错误显示Unrecognized grouping construct。我的模式错了吗?

   WebClient client = new WebClient();
            string contents = client.DownloadString("http://site.com");

                string pattern =@"<td>\s*(?<no>\d+)\.\s*</td>\s*<td>\s*
                        <a class=""LN"" href=""[^""]*+"" 
                        onclick=""[^""]*+"">\s*+<b>(?<name>[^<]*+)
                        </b>\s*+</a>.*\s*</td>\s*+ 
                        <td align=""center"">[^<]*+</td>
                        \s*+<td>\s*+(?<locations>(?:<a href=""[^""]*+"">[^<]*+</a><br />\s*+)++)</td>";

            foreach (Match match in Regex.Matches(contents, pattern, RegexOptions.IgnoreCase))
            {
                string no = match.Groups["no"].Value;
                string name = match.Groups["name"].Value;
                string locations = match.Groups["locations"].Value;

                Console.WriteLine(no+" "+name+" "+locations);
            }
4

1 回答 1

1

?P<name>在 C#/.NET 中没有这样的东西。等效的语法只是?<name>.

命名组P语法来自 PCRE/Python(Perl 允许它作为扩展)。

您还需要删除所有嵌套的量词(即更改为*+*)。如果您想获得完全相同的行为,您可以切换到,同样使用.+++X*+(?>X*)++

这是您的正则表达式,已修改。我也尝试过评论它,但我不能保证我这样做不会破坏它。

new Regex(
@"<td>                   # a td element
    \s*(?<no>\d+)\.\s*   # containing a number captured as 'no'
  </td>\s*
  <td>\s*                # followed by another td, containing
                         # an <a href=... onclick=...> exactly
      <a class=""LN"" href=""(?>[^""]*)"" onclick=""(?>[^""]*)""> 
         (?>\s*)                   # which contains
         <b>(?<name>(?>[^<]*))</b> # some text in bold captured as 'name'
         (?>\s*)
      </a>
      .*                 # and anywhere later in the document
      \s*
  </td>                  # the end of a td, followed by whitespace
  (?>\s*)   
  <td align=""center"">  # after a <td align=center> containing no other elements
    (?>[^<]*)
  </td>
  (?>\s*)
  <td>                   # lastly 
    (?>\s*)
    (?<locations>        # a series of <a href=...>...</a><br/>
        (?>(?:           # captured as 'locations'
            <a href=""(?>[^""]*)"">(?>[^<]*)</a>
            <br />
            (?>\s*)
            )
        +))              # (containing at least one of these)
  </td>", RegexOptions.IgnorePatternWhitespace|RegexOptions.IgnoreCase)

但是你真的应该使用HTML Agility Pack之类的东西。

于 2013-10-25T03:34:42.743 回答