【问题标题】:Finding multiple occurrences of a word and printing out the entire line in which the word exists using c-sharp查找一个单词的多次出现并使用 c-sharp 打印出该单词所在的整行
【发布时间】:2021-04-18 09:08:27
【问题描述】:

嘿,伙计们,这是我一段时间以来一直想做的事情...... 所以我有一个在线文本文件,可以通过这样的链接访问https://example.com/myfile.txt 文本文件包含几句,这里有几句

This is a sentence
sentences are a combination of multiple words
we cannot imagine a world without sentences
words together form a sentence
here's a sentence orange is a fruit and I love it!
how's the day today?

好的,这是文本文件中的所有随机句子,所以现在如果我在输入 (string input) 中输入单词“单词”,我希望它打印出包含输入的所有行,这是一个示例

sentences are a combination of multiple words
words together form a sentence

【问题讨论】:

  • 这是一个陈述,而不是一个问题。其中哪一部分给您带来了问题?
  • 我在做这件事时遇到了麻烦,我不知道如何处理它,现在我有了清晰的工作代码来学习和理解,感谢 Poul Bak

标签: c# .net string


【解决方案1】:

这是使用Regex 的明显案例。

using System.Text.RegularExpression;

string text = @"This is a sentence
sentences are a combination of multiple words
we cannot imagine a world without sentences
words together form a sentence
here's a sentence orange is a fruit and I love it!
how's the day today?";

string input = "words";
Regex regex = new Regex(@"^.*" + input + @".*$", RegexOptions.Multiline);
foreach (Match match in regex.Matches(text))
{
    Console.WriteLine(match.value);
}

解释: @"^.*" + input + @".*$", RegexOptions.Multiline

^.* 从行首匹配零个或多个字符

input匹配input字符串中的字符串

.*$ 匹配行尾的零个或多个字符

RegexOptions.Multiline 使^$ 匹配行的开头和结尾(通常它们匹配整个文本的开头和结尾)。

【讨论】:

  • 非常感谢你的朋友,真的很期待一个好的解决方案,你终于给了我一个!
  • 谢谢,伙计,它解决了我的问题,我很想请你喝杯咖啡
  • input 需要清理。它可以包含任何正则表达式字符。使用Regex.Escape(input)
  • @PoulBak 是的,你想捕获整行,我一开始没明白
  • 喂,对不起,我不是故意的,是我哥,对不起!
【解决方案2】:

所以,只是为了好玩,您可以使用这些函数(它们按照您的要求执行,第二个函数允许您传递 URI,以便它从网址下载文本文件并继续搜索.

public static global::System.Collections.Generic.List<string> SearchFor(string[] Lines, string Term)
{
    global::System.Collections.Generic.List<string> r = new global::System.Collections.Generic.List<string>(Lines.Length);
    foreach (string l in Lines) { if (l.Contains(Term)) { r.Add(l.Trim()); } }
    r.TrimExcess();
    return r;
}

public static global::System.Collections.Generic.List<string> SearchFor(string Text, string Term, bool TextIsUri = false)
{
    if (TextIsUri) { using (global::System.Net.WebClient w = new global::System.Net.WebClient()) { Text = w.DownloadString(new global::System.Uri(Text)); } }
    return SearchFor(Text.Split(new char[] { '\n' }, global::System.StringSplitOptions.RemoveEmptyEntries), Term);
}

当然,您还可以提供一些安全措施,例如测试字符串是否为空等,但我没有使用它,因此您可以查看最简单的代码并对其进行改进。

【讨论】:

  • 不下载,只读,所以每次程序需要检查网络需要可用的东西时,如果没有它就不会工作
  • 也没有问题,这只是一个替代方案,但如果你调用 "SearchFor("example.com/mytext.txt", "word", true)" 将访问网络,获取内存中的文件并应用过滤器,如果调用 "SearchFor("word bla, of bla bla word word", "word", false)" 它将直接过滤文本,而不是从任何地方获取它,使用 "Text" 参数作为要过滤的内容(也可以轻松更改它以从文件路径获取)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 2018-09-23
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多