如何使用正则表达式和相交函数从文件中分离关键字

How to use Regular expression and Intersect function to separate keywords from a file

我想读取两个文件,一个是 .c 文件,另一个是 .csv 文件。现在 .csv 有一个 C 关键字列表。我想将这些 C 关键字与 .c 程序和 select 仅关键字匹配并显示在控制台上。

也许这是一项简单的任务,但我不明白。

使用下面的代码,我能够获取 char 数组中的所有字母,但现在这是一个字符串,如何将它们与特定单词匹配,select 仅匹配字符串中的单词。还有其他办法吗

class FileReader
{
    static void Main(string[] args)
    {
        string[] cprglines = File.ReadAllLines("E:\cprogram\cpro\fact.c");
        string[] ckeywordslines = File.ReadAllLines("E:\ckeywords.csv");

        string letters = string.Empty;
        List<string> list = new List<string>();

        foreach (string a in cprglines)
        {
           foreach (char c in a)
            {
                if (Char.IsLetter(c))
                {
                    letters += c;
                }
            }

            list.Add(letters);
        }

        string[] arr = list.ToArray();

        foreach (string a1 in arr)
        {
            Console.WriteLine(a1);
        }

        Console.ReadKey();
    }
}

你的错误在这里

foreach (string a in cprglines)
        {
           foreach (char c in a)
            {
                if (Char.IsLetter(c))
                {
                    letters += c;
                }
            }

            list.Add(letters);
        }

这里不写代码了,太费时间了。但是我会告诉你怎么写。

  1. 拆分字符串并获取单个单词
  2. 检查每个单词 ()#;-+/% .如果是这样,请删除那些特殊字符。
  3. 现在检查它是否在 C 关键字列表中。
  4. 如果有,请将其添加到您的列表中。

如果我没有正确理解你的问题。这可能对你有用

string contentinc = @"#include <stdio.h> int main() {     int number;     printf('Enter an integer: ');     scanf('%d', &number);    // True if the number is perfectly divisible by 2    if(number % 2 == 0)        printf('%d is even.', number);    else        printf('%d is odd.', number);    return 0;}";
string contectincsv = "include, main, number, there are, some thing, scanf, true";
contentinc = Regex.Replace(contentinc, @"[^0-9a-zA-Z ]+", " ");
List<string> listofc = contentinc.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
List<string> listofcsv = contectincsv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToList();
List<string> Commonlist = listofcsv.Intersect(listofc).ToList();