2012-01-08 101 views
0

雖然我現在在文本文件中使用「#」作爲分隔符,但我通常會將文本文件中的一些字符串逐行添加到列表或數組中。如何將兩個字符串「softpedia.com」和「download.com」以兩個「#」符號作爲切入點讀入列表?請記住,在兩次哈希之間可能存在更多或更少的字符串。在C#中提取文本文件的特定部分

例如,

# Internal Hostnames 
softpedia.com 
download.com 
# External Hostnames 

預期輸出:

softpedia.com 
download.com 
+0

使用'#'作爲開始標記會導致'Internal Hostnames'也成爲結果的一部分。 – Oded 2012-01-08 21:04:25

+0

@Oded,我如何阻止它被包含? – 2012-01-08 21:09:58

+0

我的觀察是,使用'#'本身與使用'#'開始使用'#'有區別。 – Oded 2012-01-08 21:11:20

回答

2
class Program 
{ 
    static void Main() 
    { 
     using (var reader = File.OpenText("test.txt")) 
     { 
      foreach (var line in Parse(reader)) 
      { 
       Console.WriteLine(line); 
      } 
     } 
    } 

    public static IEnumerable<string> Parse(StreamReader reader) 
    { 
     string line; 
     bool first = false; 
     while ((line = reader.ReadLine()) != null) 
     { 
      if (!line.StartsWith("#")) 
      { 
       if (first) 
       { 
        yield return line; 
       } 
      } 
      else if (!first) 
      { 
       first = true; 
      } 
      else 
      { 
       yield break; 
      } 
     } 
    } 
} 

,如果你想只讓他們在一個列表:

using (var reader = File.OpenText("test.txt")) 
{ 
    List<string> hostnames = Parse(reader).ToList(); 
} 
+0

嗨,謝謝,但是這不包括輸出中的「內部主機名」? – 2012-01-08 21:10:35

+0

@JamesTeare,你只需要內部主機名? – 2012-01-08 21:11:26

+0

@JamesTeare - 它沒有。它正在用'#'開始檢查_lines。 – Oded 2012-01-08 21:11:48

0

這聽起來像你想讀的所有線路在一組#開始行之間。如果是這樣,請嘗試以下內容

List<string> ReadLines(string filePath) { 
    var list = new List<string>(); 
    var foundStart = false; 
    foreach (var line in File.ReadAllLines(filePath)) { 
    if (line.Length > 0 && line[0] == '#') { 
     if (foundStart) { 
     return list; 
     } 
     foundStart = true; 
    } else if (foundStart) { 
     list.Add(line); 
    } 
    } 
    return line; 
} 
1

將其讀入緩衝區並讓正則表達式執行此操作。

string input = @" 
# Internal Hostnames 
softpedia.com 
download.com 
# External Hostnames  
"; 
string pattern = @"^(?!#)(?<Text>[^\r\s]+)(?:\s?)"; 

Regex.Matches(input, pattern, RegexOptions.Multiline) 
    .OfType<Match>() 
    .Select (mt => mt.Groups["Text"].Value) 
    .ToList() 
    .ForEach(site => Console.WriteLine (site)); 

/* Outputs 
softpedia.com 
download.com 
*/