【问题标题】:Read a specific word from textual file从文本文件中读取特定单词
【发布时间】:2017-12-20 09:07:47
【问题描述】:

我想做一个 C# 应用程序,它从文件中读取,查找特定的字符串(单词)。我不知道那会怎样。

我的文件如下所示:

hostname: localhost

我怎样才能只阅读“本地主机”部分?

using (StreamReader sr = File.OpenText(config))
{
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
        string hostname = s;
        Console.WriteLine(hostname);
    }
}

^(up) 从文件中读取所有内容。

【问题讨论】:

  • 你想达到什么目的?您是否试图确定文本文件是否包含单词 localhost?或者你想获取主机名,在这个例子中是 localhost?
  • 如果您要检查文件是否包含特定单词,请遍历所有行并调用 line.contains()。
  • 您是否考虑过使用正则表达式进行匹配和捕获?例如:regex101.com/r/KsAHO4/1
  • @spreson 我正在尝试获取 'localhost' 行。@Fang 你也可以给我一个例子吗?

标签: c# string


【解决方案1】:

根据您的代码,您将文件内容存储在string hostname,所以现在您可以像这样拆分您的hostname

String[] byParts = hostname.split(':')

byPart[1] will contain 'locahost' <br/>
byPart[0] will contain 'hostname'<br/>


或者,如果您有这样的情况,您将始终使用hostname: localhost 获取文件,那么您可以使用:

hostname.Contains("localhost")


接下来您可以使用if() 来比较您的逻辑部分。

希望对你有帮助。

【讨论】:

  • 如果您还有任何疑问,请随时提问 :)
  • 感谢您的回复。但我觉得你不是很了解我。我正在寻找从中获取“本地主机”一词。假设我有一个基于 .txt 文件的帐户;用户名:Luke -> 我只想要卢克密码:tesd -> 我只想要“testd”字
  • 是的,因为上面的代码也可以工作。您将在拆分数组中拥有字符串的两个部分。 byPart[1] will contain 'locahost' byPart[0] will contain 'hostname。因此,在您给定的示例中,username: Luke byPart[0] 将包含“用户名”,而 byPart[1] 将包含“Luke”。
  • String[] byParts = hostname.Split(':');改成string[] byParts = hostname.Split(':');试试
  • @mayak 还是一样。
【解决方案2】:
using (var sr = File.OpenText(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("localhost"))
        {
            Console.WriteLine(line);
        }
    }
}

这将逐行读取文件,如果该行包含 localhost,它将将该行写入控制台。这当然会遍历所有行,您可能想在找到行后中断或做其他事情。与否,取决于您的要求。

【讨论】:

    【解决方案3】:

    这是未经测试的!

    下面的 sn-p 利用了 Regex 的捕获组功能。它将在当前行中查找完全匹配。如果匹配成功,则会打印出捕获的值。

    // Define regex matching your requirement
    Regex g = new Regex(@"hostname:\s+(\.+?)"); // Matches "hostname:<whitespaces>SOMETEXT" 
                                                // Capturing SOMETEXT as the first group
    using (var sr = File.OpenText(path))
    {
        string line;
        while ((line = sr.ReadLine()) != null) // Read line by line
        {
            Match m = g.Match(line);
            if (m.Success)
            {
                // Get value of first capture group in regex
                string v = m.Groups[1].Value;
                // Print Captured value , 
                // (interpolated string format $"{var}" is available in C# 6 and higher)
                Console.WriteLine($"hostname is {v}"); 
                break; // exit loop if value has been found
                       // this makes only sense if there is only one instance
                       // of that line expected in the file.
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多