为什么我的正则表达式在正则表达式测试网站上找到匹配项,但在我的程序中却找不到?

问题描述 投票:0回答:1

我正在用 C# 编写 ASP.NET Core 8.0 Web API。该 API 应该运行 CMD 行实用程序并将输出保存到我想要格式化的文本文件中。我想要格式化文本文件的第一种方法是应用正则表达式用与我的正则表达式匹配的行覆盖文本文件。

我已经使用 Regex101 来针对我的文本文件的未格式化版本测试我的正则表达式,它与它应该匹配的内容相匹配。但是,我在程序中实现的解决方案是返回整个文本文件,而不仅仅是正则表达式中的匹配项。

保存文本文件后,我有两行声明正则表达式模式并调用一个函数,该函数将匹配的文本存储在名为matchedLines的变量中。

注意:我临时在

FilterOutput
函数中设置了不同的输出位置,以确保我的正则表达式实际上与我想要的文本匹配。一旦我知道正则表达式正常工作,我计划使用与原始文本文件相同的输出位置。

这是两行:

Regex regexPattern = new Regex("""Users of [NXSC]+\d{5}[: ]+\(Total of \d{1,7} licenses? issued;  Total of \d{1,4} licenses? in use\)\n{2}  "[NXSC]+\d{5}" v[\d.]+, vendor: ugslmd, expiry: [\d\w\-]+\n[ \w]+\n{2}( {4}[\w\d .()/,:]+\n){1,999}""", RegexOptions.Multiline);

// filePath is where the text file is being stored
FilterOutput(filePath, regexPattern);

这是函数:

private void FilterOutput(string filePath, Regex pattern)
{
    string[] lines = System.IO.File.ReadAllLines(filePath);

    List<string> matchedLines = new List<string>();

    foreach (string line in lines)
    {
        MatchCollection matches = pattern.Matches(line);
        matchedLines.Add(line);
    }

    System.IO.File.WriteAllLines($"output_Directory\\regex_Output.txt", matchedLines);
}

以前,我的函数看起来像这样,但返回数据看起来与上面的函数相同。

private void FilterOutput(string filePath, string pattern)
{
    string[] lines = System.IO.File.ReadAllLines(filePath);

    List<string> matchedLines = new List<string>();

    foreach (string line in lines)
    {
        MatchCollection matches = Regex.Matches(line, pattern);
        matchedLines.Add(line);
    }

    System.IO.File.WriteAllLines($"outputDirectory\\regex_Output.txt", matchedLines);
}

我的变量

matchedLines
以某种方式包含整个文本文件,而不仅仅是匹配的文本。我很确定我的问题出在
FilterOutput
函数中的某个地方,但我可以使用一些帮助来准确识别导致我的正则表达式失败的原因。

c# asp.net-core-webapi .net-8.0
1个回答
0
投票

重读你的代码。

您的代码循环遍历输入的每一行,然后调用

pattern.Matches(line)
(其结果从未实际使用过),然后将该行添加到
matchedLines
,无论该行是否与正则表达式匹配。

private void FilterOutput(string filePath, Regex pattern)
{
    string[] lines = System.IO.File.ReadAllLines(filePath);

    List<string> matchedLines = new List<string>();

    foreach (string line in lines)
    {
        MatchCollection matches = pattern.Matches(line);

        // note that there is no conditional here. Every line will be added to matchedLines        
        matchedLines.Add(line);
    }

    System.IO.File.WriteAllLines($"output_Directory\\regex_Output.txt", matchedLines);
}

我假设您只想将行添加到

matchedLines
(如果它确实匹配)。所以你会在循环中想要这样的东西:

    foreach (string line in lines)
    {
        if(pattern.IsMatch(line)){
           matchedLines.Add(line);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.