相关疑难解决方法(0)

从文本文件中读取固定宽度记录

我有一个充满记录的文本文件,其中每个记录中的每个字段都是固定宽度.我的第一种方法是使用string.Substring()解析每条记录.有没有更好的办法?

例如,格式可以描述为:

<Field1(8)><Field2(16)><Field3(12)>
Run Code Online (Sandbox Code Playgroud)

并且具有两个记录的示例文件可能如下所示:

SomeData0000000000123456SomeMoreData
Data2   0000000000555555MoreData    
Run Code Online (Sandbox Code Playgroud)

我只是想确保我没有忽略比Substring()更优雅的方式.


更新: 我最终选择了Killersponge建议的正则表达式:

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

然后我使用以下内容访问字段:

Match match = reLot.Match(record);
string field1 = match.Groups["Field1"].Value;
Run Code Online (Sandbox Code Playgroud)

.net c# parsing fixed-width

18
推荐指数
3
解决办法
3万
查看次数

删除随机空格

所有,

我有一些索引文本,我想用更统一的庄园格式化.例如:

I    live in  Virginia   and it is  raining     today
Run Code Online (Sandbox Code Playgroud)

我希望打印出来

I live in Virginia and it is raining today
Run Code Online (Sandbox Code Playgroud)

我正在用Python编写我的应用程序,所以如果有人知道如何进行这种字符串操作,那将非常感激.

亚当

python regex whitespace

1
推荐指数
1
解决办法
1250
查看次数

标签 统计

.net ×1

c# ×1

fixed-width ×1

parsing ×1

python ×1

regex ×1

whitespace ×1