C#正则表达式捕获一切

时间:2016-04-17 02:09:17

标签: c# regex

我想只在括号之间插入文字,但由于某种原因,它给了我整件事

这是我写的正则表达式

<a href='ete(.+)'>det

这是字符串

</td>
<td>
<a href='ete/d1460852470.html'>detailed list #11</a> (20.94KB)
</td>
<td>
392
</td>
<td>
4/17 12:21:10 am
</td>
</tr>
<tr>
<td>
<a href='ete/1460845272.html'>ete #5</a> (6.71KB)
</td>
<td>
<a href='ete/d1460845272.html'>detailed list #5</a> (19.76KB)
</td>
<td>
372
</td>
<td>
4/16 10:21:12 pm
</td>
</tr>
<tr>
<td>
<a href='ete/1460839272.html'>ete #2</a> (6.62KB)
</td>
<td>
<a href='ete/d1460839272.html'>detailed list #2</a> (19.4KB)
</td>
<td>
366
</td>
<td>
4/16 8:41:12 pm
</td>
</tr>
<tr>
<td>
<a href='ete/1460830870.html'>ete #8</a> (6.72KB)
</td>
<td>
<a href='ete/d1460830870.html'>detailed list #8</a> (19.76KB)
</td>

我只想要/'

之间的文字

但现在不会发生这种情况。我找回了一个三维数组。

这是https://myregextester.com/index.php生成的代码

      String sourcestring = "source string to match with pattern";
      Regex re = new Regex(@"<a href='ete(.+)'>det");
      MatchCollection mc = re.Matches(sourcestring);
      int mIdx=0;
      foreach (Match m in mc)
       {
        for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
          {
            Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
          }
        mIdx++;
      }

2 个答案:

答案 0 :(得分:1)

将正则表达式更改为:

Regex re = new Regex(@"<a href='ete([^']+)'>det");

你应该得到你想要的东西。

它表示匹配组中不是结束引号的所有字符,然后匹配'>det之后的字符。

答案 1 :(得分:0)

您的答案已经在您的其中一个匹配组中 - m[n].Groups[1]将只为您提供捕获组。 m[n].Groups[0]将为您提供与正则表达式匹配的所有文本,而不仅仅是您的捕获组。

如果你想变得迂腐,你可以切换到前瞻和后视,例如(?<=<a href='ete).+(?='>det),仅匹配内部文字。

相关问题