簡體   English   中英

使用正則表達式從ftpwebrequest解析文件

[英]using regex to parse a file from a ftpwebrequest

我正在通過c#中的ftpwebrequest從供應商讀取數據。 因此,數據將逐行以字符串格式顯示,例如

0123030014030300123003120312030203013003104234923942348

我需要將此數據解析為適當的字段,以便隨后將它們插入sql talble。 我知道每個字段的起始位置,因此我想使用正則表達式解析每個字段。 這是我用來獲取數據的函數,現在我只需要解析數據。 我很難找到一個明確的解決方案。 任何建議將不勝感激 :)

    static void GetData()
    {
        WebClient request = new WebClient();
        string url = "ftp://ftp.WebSite.com/file";
        request.Credentials = new NetworkCredential("userid", "password");
        try
        {
            byte[] newFileData = request.DownloadData(url);
            string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
            Console.WriteLine(fileString);
        }
        catch (WebException e)
        {

        } 
    }

如果只是按指定的長度分割,則不需要使用正則表達式。 在C#中,您可以僅使用String.Substring ,例如:

byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
string fieldOne = fileString.Substring(0, n);

這是一個正則表達式的例子。 我們通過\\ d {x}的總數指定要捕獲的內容,例如\\ d {4}給我們4位數字。 然后,將其放入命名捕獲組(?<NameHere>\\d{4})然后按其名稱(在前面的文本示例中為NameHere (?<NameHere>\\d{4})訪問它進行處理。

請參閱刪除三個字段ID,組號和目標編號的示例:

string data = "0123030014030300123003120312030203013003104234923942348";

string pattern = @"^(?<ID>\d{4})(?<Group>\d{3})(?<Target>\d{8})";

Match mt = Regex.Match(data, pattern);

// Writes
// ID: 0123 of Group 030 on Target: 01403030
Console.WriteLine("ID: {0} of Group {1} on Target: {2}", mt.Groups["ID"].Value, mt.Groups["Group"].Value, mt.Groups["Target"].Value);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM