Reputation: 1300
Need help..Why do i get an ArgumentException was Unhandle.
the error shows Unrecognized grouping construct
. Is my pattern wrong?
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);
}
Upvotes: 1
Views: 1091
Reputation: 30590
There's no such thing as ?P<name>
in C#/.NET. The equivalent syntax is just ?<name>
.
The P
named group syntax is from PCRE/Python (and Perl allows it as an extension).
You'll also need to remove all nested quantifiers (i.e. change *+
to *
and ++
to +
). If you want to get the exact same behavior you can switch X*+
to (?>X*)
, and likewise with ++
.
Here is your regex, modified. I've tried to comment it a bit too, but I can't guarantee I did so without breaking it.
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)
But you really should use something like the HTML Agility Pack.
Upvotes: 1