programing

에서 명명된 캡처 그룹에 액세스하려면 어떻게 해야 합니까?NET 정규식?

telebox 2023. 5. 7. 11:23
반응형

에서 명명된 캡처 그룹에 액세스하려면 어떻게 해야 합니까?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> 

저는 여러 웹사이트에서 발견한 몇 가지 다른 "방법"을 실험해 보았지만 계속해서 같은 결과를 얻습니다.

정규식에 지정된 명명된 캡처 그룹에 액세스하려면 어떻게 해야 합니까?

Match 개체의 그룹 컬렉션을 사용하여 캡처 그룹 이름으로 인덱싱합니다(으)로 인덱싱합니다.

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를 반환합니다.일치하는 경우 outparam에는 각각 링크와 이름이 포함됩니다.

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

이 답변은 라쉬미 판디트의 답변보다 개선되는데, 질문에 자세히 설명된 정확한 문제를 완전히 해결하는 것처럼 보이기 때문에 다른 답변보다 어느 정도 더 좋습니다.

단점은 비효율적이고 케이스 무시 옵션을 일관되게 사용하지 않는다는 것입니다.

비효율적인 부분은 정규식을 구성하고 실행하는 데 비용이 많이 들 수 있기 때문이며, 그 답변에서 정규식은 단 한 번만 구성되었을 수 있습니다(통화).Regex.IsMatch현장 뒤에서 정규식을 다시 만들고 있었습니다.)그리고.Match메서드는 한 번만 호출되고 변수에 저장될 수 있습니다.link그리고.name전화해야 합니다Result그 변수로부터.

그리고 IgnoreCase 옵션은 다음과 같은 경우에만 사용되었습니다.Match부분적이지만 그렇지 않은Regex.IsMatch일부.

나는 또한 Regex 정의를 단 한 번만 구성하기 위해 메서드 외부로 이동했습니다(나는 만약 우리가 어셈블리를 저장하고 있다면 합리적인 접근법이라고 생각합니다)RegexOptions.Compiled옵션)을 선택합니다.

private static Regex hrefRegex = new Regex("<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>",  RegexOptions.IgnoreCase | RegexOptions.Compiled);

public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
    var matches = hrefRegex.Match(htmlTd);
    if (matches.Success)
    {
        link = matches.Result("${link}");
        name = matches.Result("${name}");
        return true;
    }
    else
    {
        link = null;
        name = null;
        return false;
    }
}

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

반응형