【问题标题】:C# String manipulationC# 字符串操作
【发布时间】:2010-10-20 17:00:59
【问题描述】:

我正在开发一个从页面上的文本文件中获取文本的应用程序。 示例链接: 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());
                    }
                }
            }

这显然行不通,但你明白了。

提前谢谢你!

【问题讨论】:

  • 考虑一个基于正则表达式的解决方案。

标签: c# regex web-applications .net-3.5 downloadstring


【解决方案1】:

这应该可行:

        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);
            }
        }

【讨论】:

  • 非常感谢!我不知道你可以在正则表达式中使用通配符,这实际上很有意义。 :D 我会尽快将其标记为答案。感谢您的快速响应。
【解决方案2】:

我很想对这类事情使用正则表达式。

有点像

Stuff[^\s]*.rar

将只提取您需要的文本。

这样的功能怎么样:

public static IEnumerable<string> GetStuff(string fileName)
{
    var regex = new Regex(@"Stuff[^\s]*.rar");
    using (var reader = new StreamReader(fileName))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            var match = regex.Match(line);
            if (match.Success)
            {
                yield return match.Value;
            }
        }
    }
}

【讨论】:

  • 感谢您的帮助,我决定使用上面的代码,因为它可以工作并且不占用空间。但再次感谢,我很感激。
  • 没问题 - 事实上,您经常会收到多个建议并且您可以选择最适用的,这是 SO 的优势之一恕我直言。
【解决方案3】:
for(string line in text)
{
    if(line.EndsWith(".rar"))
    {
        int index = line.LastIndexOf("Stuff");
        if(index != -1)
        {
            listBox1.Items.Add(line.Substring(index));
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2012-10-20
    • 2012-09-26
    相关资源
    最近更新 更多