阅读从文本文件固定宽度记录 [英] Read fixed width record from text file

查看:268
本文介绍了阅读从文本文件固定宽度记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,全面记录,其中每个记录中每个字段是一个固定的宽度。我的第一个办法是分析简单地使用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.

这篇关于阅读从文本文件固定宽度记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆