阅读从文本文件固定宽度记录宽度、文本文件

由网友(抢我辣条还敢跑)分享简介:我有一个文本文件,全面记录,其中每个记录中每个字段是一个固定的宽度。我的第一个办法是分析简单地使用string.Substring()每个记录。有没有更好的办法? 例如,格式可以被描述为:<字段1(8)><场2(16)><字段3(12)>和两个记录一个例子文件可能如下:SomeDat...

我有一个文本文件,全面记录,其中每个记录中每个字段是一个固定的宽度。我的第一个办法是分析简单地使用string.Substring()每个记录。有没有更好的办法?

例如,格式可以被描述为:

 <字段1(8)><场2(16)><字段3(12)>
 

和两个记录一个例子文件可能如下:

  SomeData0000000000123456SomeMoreData
数据2 0000000000555555MoreData
 
固定宽度文件输出为文本文件

我只是想确保我不要忽略一个更优雅的方式比子串()。

更新:我最终去与像Killersponge正则表达式提示:

 私人只读正则表达式reLot =新的正则表达式(REGEX_LOT,RegexOptions.Compiled);
常量字符串REGEX_LOT =^(小于?字段1> {6})+
                        (小于?字段2> {16})+
                        (小于?字段3> {12});
 

我然后使用以下方法来访问字段:

 匹配匹配= reLot.Match(记录);
字符串字段1 = match.Groups [字段1]值。
 

解决方案

子字符串听起来不错。唯一的缺点我能立刻想到的是,这意味着每次复制数据,但我不会担心,直到你证明这是一个瓶颈。子串很简单:)

您的可以的使用正则表达式匹配整个记录的时间和捕获等领域,但我认为这将是矫枉过正。

I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way?

For example, the format could be described as:

<Field1(8)><Field2(16)><Field3(12)>

And an example file with two records could look like:

SomeData0000000000123456SomeMoreData
Data2   0000000000555555MoreData

I just want to make sure I'm not overlooking a more elegant way than Substring().

Update: I ultimately went with a regex like Killersponge suggested:

private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled);
const string REGEX_LOT = "^(?<Field1>.{6})" +
                        "(?<Field2>.{16})" +
                        "(?<Field3>.{12})";

I then use the following to access the fields:

Match match = reLot.Match(record);
string field1 = match.Groups["Field1"].Value;

解决方案

Substring sounds good to me. The only downside I can immediately think of is that it means copying the data each time, but I wouldn't worry about that until you prove it's a bottleneck. Substring is simple :)

You could use a regex to match a whole record at a time and capture the fields, but I think that would be overkill.

阅读全文

相关推荐

最新文章