如何显示文件中特定单词的所有出现 C#

How to display all occurrences of specific words in a file C#

我正在尝试使用 OpenFileDialog 从文件中读取所有文本/行(不管是什么类型的文件),并仅提取 C# 关键字(我已经将关键字输入a string) -但是,我似乎无法弄清楚如何提取所有事件。我不想数它们,比如 count++,我想在 RichTextBox

中显示出现的次数

这是只有第一次出现的代码:

        string keywords = @"\b(default|delegate|do|else|event|explicit|extern|false|finally|fixed|for|foreach|goto|if|implicit|in|interface|internal|is|lock|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sealed|sizeof|stackalloc|switch|this|throw|true|try|typeof|unchecked|unsafe|using|virtual|volatile|while)\b";         
        MatchCollection matches = Regex.Matches(File.ReadAllText(ofdd.FileName), keywords);              
        foreach (Match match in matches)
        {
            richTextBox1.Text = (match.Groups[1].Value);
        }

-我知道我忘记了 abstract 等关键字

该代码只执行部分工作 :( 我需要它来显示所有出现的 keywords string

知道如何显示 ALL 次出现吗?

我最终根据不同网站上的许多不同答案创建了这段代码,并且它完美运行:

               string[] keys = { "abstract", "as", "base", "break", "case", "catch", "checked", "continue", "default", "delegate", "do", "else", "event", "explicit", "extern", "false", "finally", "fixed", "for", "foreach", "goto", "if", "implicit", "in", "interface", "internal", "is", "lock", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sealed", "sizeof", "stackalloc", "switch", "this", "throw", "true", "try", "typeof", "unchecked", "unsafe", "using", "virtual", "volatile", "while" };

                    char[] separators = new char[] { ',', ' ', '\r', '\n', '.' };

                    String[] strings = data.Split(separators);
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (var item in strings)
                    {
                        if (keys.Contains(item))
                        {
                            stringBuilder.Append(item + " ");
                            count = item.Length;
                        }
                    }
                    string theOutputDesire = stringBuilder.ToString();

data 将是输入,例如如果文件或字符串包含 publicpeopleempty,则只会显示 public

count 是文件中出现的次数,例如如果文件包含 publicpublicpeople,则 count 将是 2.

keys 包含我们要查找的文本。它可以根据您的需要进行修改。

我希望这对寻找答案的其他人有所帮助!