如何从文本文件中解析它

时间:2017-07-20 15:35:42

标签: c#

我在从文本文件解析下面的示例时遇到问题。我试图做的是读取整个文本文件,然后将文件拆分,这样每个数字都是一个单独的元素。

所以它是这样的:

[466 474 482]

[24 8 29]

[50 46 3]

到此

[466],[474],[482],[24,[8],[29],[50],[46],[3]

我的计划是使用ReadAllLines读取文本,然后使用Split方法单独拆分数字

string[] textFile = File.ReadAllLines(@"path");
string[] textFile2 = { };

for (int i = 0; i < textFile.Length; i++)
{
     textFile2 = textFile[i].Split(' ');
}

foreach (string number in textFile2)
{
     Console.Write(number + " ");
}

但我最终得到了这[50] [46] [3]。

3 个答案:

答案 0 :(得分:2)

您正在为您阅读的每一行替换textFile2个内容。请尝试使用List<string>

string[] textFile = File.ReadAllLines(@"path");
List<string> textFile2 = new List<string>();

for (int i = 0; i < textFile.Length; i++)
{
    textFile2.AddRange(textFile[i].Split(' '));
}

foreach (string number in textFile2)
{
    Console.Write(number + " ");
}

如果您的文件看起来真的如此,使用方括号和空行,这可能会对您有所帮助:https://dotnetfiddle.net/fzBU4W

答案 1 :(得分:0)

我更喜欢使用正则表达式。

确保在代码顶部调用Regex名称空间:

using System.Text.RegularExpressions;

将正则表达式实例定义为静态字段 - 如果您以高频率使用它,这是个好主意。

public static Regex extractNumberRegex = new Regex("([\\d]+)[\\s]?");

下面的示例定义了静态类中的扩展方法。 首先,让我们从字符串中提取数字。

public static List<String> extractNumbers(this String source)
{
   List<String> output = new List<string>();

   MatchCollection mchCol = extractNumberRegex.Matches(source);
   foreach (Match mch in mchCol)
   {
       output.Add(mch.Value);
   }
   return output;
}

您的主要方法(此处也是扩展名):

public static List<String> extract(this String path)
{
    String[] lines = File.ReadAllLines(path);
    foreach (String ln in lines)
    {
       List<String> numers = ln.extractNumbers();
       String reformatLine = "";
       foreach (String num in numers)
       {
           reformatLine = reformatLine + "[" + num + "] ";
       }
       reformatLine = reformatLine.Trim();

       Console.WriteLine(reformatLine);
    }

}

答案 2 :(得分:0)

您可以连接输入数组,然后按char分割。

string[] textFile = File.ReadAllLines(@"path");
string concatInput = String.Join(" ", textFile);
string[] textFile2 = concatInput.Split(' ');

foreach (string number in textFile2)
{
     Console.Write(number + " ");
}

如果你想删除括号[],你可以做这样的事情......

string concatInput = String.Join(" ", textFile).Replace('[', ' ').Replace(']', ' ');
string[] textFile2 = concatInput.Split(' ').Where(x => x != "").ToArray();
相关问题