IT story

.NET 정규식에서 명명 된 캡처 그룹에 어떻게 액세스합니까?

hot-time 2020. 4. 5. 20:35
반응형

.NET 정규식에서 명명 된 캡처 그룹에 어떻게 액세스합니까?


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());

그러나 이것은 항상 전체 라인을 보여줍니다.

<td><a href="/path/to/file">Name of File</a></td> 

다양한 웹 사이트에서 찾은 몇 가지 다른 "방법"을 실험했지만 동일한 결과를 계속 얻습니다.

정규식에 지정된 명명 된 캡처 그룹에 어떻게 액세스 할 수 있습니까?


일치 개체의 그룹 모음을 사용하여 캡처 그룹 이름으로 색인을 생성하십시오 (예 :

foreach (Match m in mc){
    MessageBox.Show(m.Groups["link"].Value);
}

명명 된 캡처 그룹 문자열을 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);
        }
    }
}

다음 코드 샘플은 사이에 공백 문자가있는 경우에도 패턴과 일치합니다. 즉 :

<td><a href='/path/to/file'>Name of File</a></td>

만큼 잘:

<td> <a      href='/path/to/file' >Name of File</a>  </td>

메소드는 입력 htmlTd 문자열이 패턴과 일치하는지 여부에 따라 true 또는 false를 리턴합니다. 일치하면 출력 매개 변수에 각각 링크와 이름이 포함됩니다.

/// <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;
}

나는 이것을 테스트했고 올바르게 작동합니다.


또한 누군가 Regex 객체에서 검색을 실행하기 전에 그룹 이름이 필요한 유스 케이스가있는 경우 다음을 사용할 수 있습니다.

var regex = new Regex(pattern); // initialized somewhere
// ...
var groupNames = regex.GetGroupNames();

참고 URL : https://stackoverflow.com/questions/906493/how-do-i-access-named-capturing-groups-in-a-net-regex

반응형