在命名捕获中获取表达式

Joh*_*rtz 5 c# regex

我提供了一个文本框,用于输入正则表达式以匹配文件名.我计划使用Regex方法检测它们提供的任何命名捕获组GetGroupNames().

我想得到他们在每个命名捕获组中输入的表达式.

例如,他们可能会输入这样的正则表达式:

December (?<FileYear>\d{4}) Records\.xlsx
Run Code Online (Sandbox Code Playgroud)

\d{4}除了手动解析正则表达式字符串之外,是否有一种方法或手段来获取子表达式?

Joh*_*rtz 1

这是一个丑陋的暴力扩展,用于解析而不使用另一个正则表达式来检测子表达式(或子模式):

    public static string GetSubExpression(this Regex pRegex, string pCaptureName)
    {
        string sRegex = pRegex.ToString();
        string sGroupText = @"(?<" + pCaptureName + ">";
        int iStartSearchAt = sRegex.IndexOf(sGroupText) + sGroupText.Length;
        string sRemainder = sRegex.Substring(iStartSearchAt);
        string sThis;
        string sPrev = "";
        int iOpenParenCount = 0;
        int iEnd = 0;
        for (int i = 0; i < sRemainder.Length; i++)
        {
            sThis = sRemainder.Substring(i, 1);
            if (sThis == ")" && sPrev != @"\" && iOpenParenCount == 0)
            {
                iEnd = i;
                break;
            }
            else if (sThis == ")" && sPrev != @"\")
            {
                iOpenParenCount--;
            }
            else if (sThis == "(" && sPrev != @"\")
            {
                iOpenParenCount++;
            }
            sPrev = sThis;
        }
        return sRemainder.Substring(0, iEnd);
    }
Run Code Online (Sandbox Code Playgroud)

用法如下:

    Regex reFromUser = new Regex(txtFromUser.Text);
    string[] asGroupNames = reFromUser.GetGroupNames();
    int iItsInt;
    foreach (string sGroupName in asGroupNames)
    {
        if (!Int32.TryParse(sGroupName, out iItsInt)) //don't want numbered groups
        {
            string sSubExpression = reParts.GetSubExpression(sGroupName);
            //Do what I need to do with the sub-expression
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,如果您想生成测试或示例数据,您可以在获得子表达式后按以下方式使用名为“Fare”的 NuGet 包:

            //Generate test data for it
            Fare.Xeger X = new Fare.Xeger(sSubExpression);
            string sSample = X.Generate();
Run Code Online (Sandbox Code Playgroud)

  • 我建议也检查转义括号 `\(` 和 `\)` (2认同)