我很难找到一个很好的资源来解释如何在C#中使用命名捕获组.这是我到目前为止的代码:
string page = Encoding.ASCII.GetString(bytePage);
Regex qariRegex = new Regex("<td><a href=\"(?<link>.*?)\">(?<name>.*?)</a></td>");
MatchCollection mc = qariRegex.Matches(page);
CaptureCollection cc = mc[0].Captures;
MessageBox.Show(cc[0].ToString());
Run Code Online (Sandbox Code Playgroud)
然而,这总是只显示整行:
<td><a href="/path/to/file">Name of File</a></td>
Run Code Online (Sandbox Code Playgroud)
我已经尝试过我在各种网站上找到的其他几种"方法",但我一直得到相同的结果.
如何访问我的正则表达式中指定的命名捕获组?
Pao*_*sco 260
使用Match对象的组集合,将其与捕获组名称索引,例如
foreach (Match m in mc){
MessageBox.Show(m.Groups["link"].Value);
}
Run Code Online (Sandbox Code Playgroud)
And*_*are 109
您可以通过将命名捕获组字符串传递给Groups
结果Match
对象的属性的索引器来指定它.
这是一个小例子:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String sample = "hello-world-";
Regex regex = new Regex("-(?<test>[^-]*)-");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(match.Groups["test"].Value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ras*_*dit 11
以下代码示例将匹配模式,即使中间有空格字符.即:
<td><a href='/path/to/file'>Name of File</a></td>
Run Code Online (Sandbox Code Playgroud)
以及:
<td> <a href='/path/to/file' >Name of File</a> </td>
Run Code Online (Sandbox Code Playgroud)
方法返回true或false,具体取决于输入htmlTd字符串是否匹配模式或否.如果匹配,则out参数分别包含链接和名称.
/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
link = null;
name = null;
string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";
if (Regex.IsMatch(htmlTd, pattern))
{
Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
link = r.Match(htmlTd).Result("${link}");
name = r.Match(htmlTd).Result("${name}");
return true;
}
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
我测试了这个,它工作正常.
归档时间: |
|
查看次数: |
194812 次 |
最近记录: |