C# 从文本文件C中提取特定单词#

C# 从文本文件C中提取特定单词#,c#,console-application,C#,Console Application,我目前正在构建一个方法,它使用streamreader遍历文本文件。我想使用正则表达式或类似的东西来更改当前的方法,您将在下面看到 using (StreamReader fs = File.OpenText(FilePath)) { int count = 0; //counts the number of times wordResponse is found. int lineNumber = 0; while (!fs.EndOf

我目前正在构建一个方法,它使用streamreader遍历文本文件。我想使用正则表达式或类似的东西来更改当前的方法,您将在下面看到

using (StreamReader fs = File.OpenText(FilePath))
    {

        int count = 0; //counts the number of times wordResponse is found.
        int lineNumber = 0;
        while (!fs.EndOfStream)
        {
            string line = fs.ReadLine();
            lineNumber++;
            int position = line.IndexOf(WordSearch);
            if (position != -1)
            {
                count++;
                Console.WriteLine("Match#{0} line {1}: {2}", count, lineNumber, line);
            }
        }

        if (count == 0)
        {
            Console.WriteLine("your word was not found!");
        }
        else
        {
            Console.WriteLine("Your word was found " + count + " times!");
        }
        Console.WriteLine("Press enter to quit.");
        Console.ReadKey();
    }
我从当前方法得到的输出是:

Match#1 line 3: Proin eleifend tortor velit, **True** quis aliquam arcu congue ut. Fusce sed mattis purus, sed vehicula diam. Nullam in leo sit amet massa pharetra semper et vel diam.
Match#2 line 7: lobortis nisl. Fusce dignissim ligula **True** a nunc maximus, vitae sollicitudin erat dictum. Vivamus commodo massa a tellus gravida posuere.
Match#3 line 17: **True** Sed pellentesque ipsum vel neque accumsan, quis fermentum augue pretium. Praesent fermentum risus nec ultricies sodales.
Match#4 line 24: Fusce nulla risus, ornare in eleifend id, **True** tincidunt eu sem. Donec enim sapien, rhoncus vitae ex lobortis, sagittis molestie libero.
Your word was found 4 times!
Press enter to quit.

正如你所看到的,我得到了整行代码,而我想要的只是每个句子中的一个单词。它现在正在搜索的单词是True

我相信是字符串
stringline=fs.ReadLine()我必须操作一些额外的步骤才能得到我想要的结果


任何提示或指针都将不胜感激。

您只需在int position=.之后添加此项即可

var word = line.SubString(position, Word.Length)
然后

它和……一样容易吗

Console.WriteLine("Match#{0} line {1}: {2}", count, lineNumber, WordSearch);
我想使用正则表达式或类似的东西

既然您提到有兴趣将当前实现更改为使用正则表达式,我将提供以下代码段:

var matches=Regex.Match(行,$”*({WordSearch})\\b.*,RegexOptions.IgnoreCase);
如果(matches.Captures.Count>0)
{
计数++;
WriteLine($“匹配#{count}行{lineNumber}:{matches.Groups[1]}”);
}        

Match
构造函数中的
RegexOption.IgnoreCase
与在表达式中添加
\b
以限制部分匹配似乎是合适的。

您能更清楚地了解您在寻找什么吗?“我只需要每个句子中的一个单词。”-哪个单词。。。您正在搜索的单词???@RyanSearle您在程序前面手动输入的单词。它查看您作为输入提供的文件的每一行,并查找您作为输入提供的特定单词。它现在正在查找的单词是真的,因为我将在问题中编辑为粗体。他没有使用或指示正则表达式。”IndexOf'类表示精确匹配,与正则表达式或类似项的部分匹配将显示'match'。有点像:“var regexPercent=newregex(“^(?)。{8,})[0-9]{1,3}(?:,?[0-9]{3})*$”)如果!regexPercent.Match(textValue).Success(做某事)'
Console.WriteLine("Match#{0} line {1}: {2}", count, lineNumber, WordSearch);