从C#中的字符串过滤字符串

时间:2014-11-26 11:01:13

标签: c# string filter substring streamreader

我正在开发一个过滤文本行的应用程序,并将过滤后的文本放入文件中。

非过滤行的示例:

0&
1&
2&
3&&&&&
4&&
5&
9&&&&&&&131015&&&&H&HEA100&1712&&1001&2&S235JR&&&HEA100 - 1712&&&&&&&S&&0.96&&&&2&&&1.7&0.2&0.2N&1001.nc

我想要做的是从该文本行中过滤H&*code*&*code1*&&*code2*&code3*&code*&&&

但在此之前,我必须将0&1&过滤到该行的H&部分。

我提出的代码(评论在荷兰抱歉):

string[] delete = new string[] { "0&", "1&", "2&", "3&&&&&", "4&&", "5&", "9&&&&&&&" };

//Geeft het pad op.
string path = @"C:\test.txt";

//Maakt een tijdelijk bestand aan
string tempFile = Path.GetTempFileName();

//Leest het bestand in vanuit het opgegeven pad
using (var sr = new StreamReader(path))

//Schrijft de string naar een tijdelijk bestand
using (var sw = new StreamWriter(tempFile))
{
    string line;
    //Checkt iedere nieuwe regel naar een van de arrays die verwijderd moeten worden
    while ((line = sr.ReadLine()) != null)
    {
        if (line != delete[0])
            if (line != delete[1])
                if (line != delete[2])
                    if (line != delete[3])
                        if (line != delete[4])
                            if (line != delete[5])
                                if (line.Substring(0, 8) != delete[6])
                                {
                                    sw.WriteLine(line);
                                }
                                else
                                {
                                    string durp = line.Substring(9);
                                    sw.WriteLine(durp);
                                }
                                if (line.StartsWith("H&") == true)
                                {
                                    MessageBox.Show(line.Substring(2, 6));
                                }
    }

    System.Threading.Thread.Sleep(1000);
    string text = System.IO.File.ReadAllText(@"C:\test.txt");

    int index = text.IndexOf('&');
    string orderNr = text.Substring(0, index);
    if (index > 0)
    {
        MessageBox.Show(orderNr);
    }

}

File.Delete(path);
File.Move(tempFile, path);

问题是我需要运行两次应用程序,因为第一次运行应用程序时它只打印0&在我的屏幕上。当我第二次运行时,131015会像我们想象的那样在我的屏幕上打印出来。

我需要提取9&&&&&&&和另一个&字符之间的数字。之后,所有&字符都需要替换为;字符。

0 个答案:

没有答案