我正在开发一个从页面上的文本文件获取文本的应用程序。 示例链接: http://test.com/textfile.txt
此文本文件包含以下文本:
1 Milk Stuff1.rar
2 Milk Stuff2.rar
3 Milk Stuff2-1.rar
4 Union Stuff3.rar
我想做的是如下所示,从每一行中删除所有内容,除了以“Stuff”开头并以“.rar”结尾的“单词”。
问题是,大多数简单的解决方案,如使用 .Remove、.Split 或 .Replace,最终都会失败。这是因为,例如,使用空格格式化字符串最终会返回:
1
Milk
Stuff1.rar\n2
Milk
Stuff2.rar\n3
Milk
Stuff2-1.rar\n4
Union
Stuff3.rar\n
我敢打赌这并不像看起来那么难,但我很感激你能给我的任何帮助。
Ps:为了清楚起见,这是我希望它返回的内容:
Stuff1.rar
Stuff2.rar
Stuff2-1.rar
Stuff3.rar
我目前正在使用这段代码:
client.HeadOnly = true;
string uri = "http://test.com/textfile.txt";
byte[] body = client.DownloadData(uri);
string type = client.ResponseHeaders["content-type"];
client.HeadOnly = false;
if (type.StartsWith(@"text/"))
{
string[] text = client.DownloadString(uri);
foreach (string word in text)
{
if (word.StartsWith("Patch") && word.EndsWith(".rar"))
{
listBox1.Items.Add(word.ToString());
}
}
}
这显然行不通,但您明白了。
提前致谢!
最佳答案
这应该有效:
using (var writer = File.CreateText("output.txt"))
{
foreach (string line in File.ReadAllLines("input.txt"))
{
var match = Regex.Match(line, "Stuff.*?\\.rar");
if (match.Success)
writer.WriteLine(match.Value);
}
}
关于C# 字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3976120/