簡體   English   中英

如何解析讀取所有行的文本文件中的特定字符串?

[英]How can i parse specific string from text file reading all lines?

在每一行中,我想解析標記后的字符串

  • 我知道它是html,但是我將html的這一部分復制到了文本文件。 例如,文本文件中的前兩行是這樣的:

     <li>602 — <a href="/w/index.php?title=Text602&amp;action=edit&amp;redlink=1" class="new" title="Text602 (page does not exist)">Text602</a> document</li> <li>ABW — <a href="/wiki/AbiWord" title="AbiWord">AbiWord</a> Document</li> 

    我想從第一行解析602,從第二行解析ABW。 我試圖做的是:

     private void ParseFilesTypes() { string[] lines = File.ReadAllLines(@"E:\\New folder (44)\\New Text Document.txt"); foreach (string str in lines) { int r = str.IndexOf("<li>"); if (r >= 0) { int i = str.IndexOf(" -", r + 1); if (i >= 0) { int c = str.IndexOf(" -", i + 1); if (c >= 0) { i++; MessageBox.Show(str.Substring(i, c - i)); } } } } } 

    但是c一直都是-1

  • 我認為正則表達式會很有用(除非沒有li屬性):

    var regex = new Regex("^<li>(.+) —");
    foreach (string str in lines)
    {
         var m = regex.Match(str);
         if (m.Success)
            MessageBox.Show(m.Groups[1].Value);
    }
    

    實際上,您的問題是您正在使用錯誤的編碼讀取文件。 你在你的文件中的特殊字符- 因此,您需要在代碼中更正此字符,並以正確的編碼讀取文件。 如果您以錯誤的編碼方式調試讀取的字符串,則會看到黑色菱形而不是

    另外,您需要先刪除空格或將i + 1替換為i

    private static void ParseFilesTypes()
    {
        string sampleFilePath = @"log.txt";
        string[] lines = File.ReadAllLines(@"log.txt", Encoding.GetEncoding("windows-1252"));
        foreach (string str in lines)
        {
            int r = str.IndexOf("<li>");
            if (r >= 0)
            {
                int i = str.IndexOf(" —", r + 1);
                if (i >= 0)
                {
    
                    int c = str.IndexOf(" —", i);
                    if (c >= 0)
                    {
                        i++;
                        int startIndex = r + "<li>".Length;
                        int length = i - startIndex - 1;
                        string result = str.Substring(r + "<li>".Length, length);
                        MessageBox.Show(result);
                    }
                }
            }
        }
    }
    

    暫無
    暫無

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

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