正则表达式匹配集合组

本文关键字:集合 正则表达式 | 更新日期: 2023-09-27 18:14:47

我已经尝试了两天来解决这个问题,我有一个MatchCollection。在模式是一个组,我想有一个列表与组的解决方案(有两个或更多的解决方案)。

string input = "<tr><td>Mi, 09.09.15</td><td>1</td><td>PK</td><td>E</td><td>123</td><td></td></tr><tr><td>Mi, 09.09.15</td><td>2</td><td>ER</td><td>ER</td><td>234</td><td></td></tr>";
string Patter2 = "^<tr>$?<td>$?[D-M][i-r],[' '][0-3][1-9].[0-1][1-9].[0-9][0-9]$?</td>$?<td>$?([1-9][0-2]?)$?</td>$?";
Regex r2 = new Regex(Patter2);
MatchCollection mc2 = r2.Matches(input);
foreach (Match match in mc2)
{
     GroupCollection groups = match.Groups;
     string s = groups[1].Value;
     Datum2.Text = s;
}

但是只有最后一个匹配(2)出现在TextBox "Datum2"中。我知道我必须使用列表框,但是Groups[1]。

谢谢你的帮助和时间。节食者

正则表达式匹配集合组

您需要在代码中纠正的第一件事是Datum2.Text = s;将覆盖Datum2中的文本,如果它有多个匹配。

现在,关于你的正则表达式

  • ^强制在行起始处匹配,所以实际上只有一个匹配。如果你把它取下来,它会匹配两次。
  • 我似乎不能理解$?在整个模式中的意图(只是把它们拿出来)。
  • [' ']匹配"引号、空格或引号"(不需要在字符类中重复字符)。
  • [0-3][1-9].[0-1][1-9].[0-9][0-9]中的所有点需要转义。点匹配其他任何字符。
  • [0-1][1-9]匹配除"10"以外的所有月份。第二个字符应为[0-9](或'd)。

代码:

string input = "<tr><td>Mi, 09.09.15</td><td>1</td><td>PK</td><td>E</td><td>123</td><td></td></tr><tr><td>Mi, 09.09.15</td><td>2</td><td>ER</td><td>ER</td><td>234</td><td></td></tr>";
string Patter2 = "<tr><td>[D-M][i-r],[' ][0-3][0-9]''.[0-1][0-9]''.[0-9][0-9]</td><td>([1-9][0-2]?)</td>";
Regex r2 = new Regex(Patter2);
MatchCollection mc2 = r2.Matches(input);
string s= "";
foreach (Match match in mc2)
{
     GroupCollection groups = match.Groups;
     s = s + " " + groups[1].Value;
}
Datum2.Text = s;
输出:

1 2

演示

你应该知道正则表达式不是解析HTML的工具。它可以在简单的情况下工作,但对于实际情况,请考虑使用HTML Agility Pack