C# 中的 reg 表达式 -- 当我组合所有条件时很难

本文关键字:组合 有条件 很难 中的 reg 表达式 | 更新日期: 2023-09-27 18:36:13

    public static string GetData(string subjectLine)
    {
        // Define the regular expression pattern. 
        string pattern = "";
        string returnString = "Error";
        Regex rgx = new Regex(pattern);
        // Find matches.
        MatchCollection matches = rgx.Matches(subjectLine);
        if (matches.Count >= 1)
        {
            return matches[0].Value;
        }
        return returnString;
    }

我已经编写了上面的方法来获取匹配的模式字符串。我单独理解所有模式匹配字符。但是当我把我所有的条件放在一起时,我就失败了。删除了我的测试模式数据,因为当我将所有条件放在一起时,我没有得到结果。

这是我正在寻找[stringData1-OnlyNumericData1-OnlyNumericData2]模式。 stringData1的最大大小限制为 10。stringData1OnlyNumericData1OnlyNumericData2中至少应该有一个字符。

  1. 这是测试主题行 [testData1-12345-678]test-1213-778] .仅返回[testData1-12345-678],第二次出现时缺少[

  2. 这是测试主题行[testData1-test12345-678Test]test-1213-778]。不返回任何内容,因为 OnlyNumericData1OnlyNumericData2 不是数字。

C# 中的 reg 表达式 -- 当我组合所有条件时很难

这个正则表达式测试,在你的整个问题上执行,只给了我 2 个匹配:

        string strRegex = @"'['w{1,10}-['d]+?-['d]+']";
        Regex myRegex = new Regex(strRegex, RegexOptions.None);
        string strTargetString = @"I have written the above method to get the matching pattern string. I understand individually all the pattern matching characters. But I am failing when I put all my conditions together. Removed my test pattern data since I am not getting the result when I put all my conditions together." + "'n'n" + @"Here is the pattern I am looking for [stringData1-OnlyNumericData1-OnlyNumericData2]. The max size limit for stringData1 is 10. At least one characters should be there in stringData1, OnlyNumericData1 and OnlyNumericData2." + "'n'n" + @"Cases" + "'n'n" + @"Here is the test subject line [testData1-12345-678] and test-1213-778]. Returns only [testData1-12345-678] and [ is missing in second occurrence." + "'n'n" + @"Here is the test subject line [testData1-test12345-678Test] and test-1213-778]. Returns nothing because OnlyNumericData1 & OnlyNumericData2 are not numeric.";
        foreach (Match myMatch in myRegex.Matches(strTargetString))
        {
            if (myMatch.Success)
            {
                // Add your code here
            }
        }

顺便说一句:这是在线dotnet正则表达式测试的好网站

public static string GetData(string subjectLine)
{
    //im not sure if you want to include numeric in the stringData1 part
    //replace [A-z'd] with [A-z] to accept only letters for stringData1
    var result = Regex.Match(subjectLine, @"'[[A-z'd]{1,10}-'d+-'d+']");
    return result.Success ? result.Value : "Error";
}

我很幸运:

'A[']['s'w-]{1,10}-[0-9]+-[0-9]+[']]