使用golang解析字符串的一种好方法是根据位置进行解析。

huangapple go评论100阅读模式
英文:

What's a good way to parse a string based on position using golang?

问题

我正在使用Go语言设计一个简单的应用程序,用于读取几种表示客户文件格式的文件。我的第一个想法是逐行读取每个文件,然后将其解析为一个结构体。到目前为止还不错,但是我需要根据索引来分割每个字段。例如:

line := "1003450020170804890000000022344"

Id从位置1到位置4 = 1003
CustomerId从位置5到7,以及与该结构相关的所有其他字段。

我想知道是否有更高效的方法来读取格式并应用于这个文件行,我考虑为每个字段创建一些结构体,并具有起始和结束字段,但这对我来说听起来有些奇怪。

type Record struct {
Id       int
Date     time.Time
Value    float64
ClientId int32
}

type RecordId struct {
  Start  int
  Finish int
  Value  int
}

type ClientId struct {
  Start  int
  Finish int
  Value  int32
}

我不知道我是否走对了方向,也许在这种情况下有更加优雅的方法可以更好地工作。

英文:

I'm designing an simple application using go to read a few file formats representing customers file formats. My first idea is to read each file line and then parse it to an struct. So far so good, but i need to split each field based on it's index. For example:

line := "1003450020170804890000000022344"

Id starts on position 1 to position 4 = 1003
CustomerId is position 5 to 7 and all other fields related to that structure.

I would like to know if there's something more efficient to read a format and apply to this file line, i thought to create some struct for each field and have the start and end fields, but it sounds weird to me.

type Record struct {
Id       int
Date     time.Time
Value    float64
ClientId int32
}

type RecordId struct {
  Start  int
  Finish int
  Value  int
}

type ClientId struct {
  Start  int
  Finish int
  Value  int32
}

I don't know if i'm on the way, maybe there's something more elegant that will work better on this case.

答案1

得分: 5

var a, b int
n, err := fmt.Sscanf("1003450020170804890000000022344", "%4d%3d", &a, &b)
if err != nil {
   // ...
}

fmt.Println(a) // 1003
fmt.Println(b) // 450

然后你可以使用这些创建一个结构体

以上是给定的代码段的翻译。

英文:
var a, b int
n, err := fmt.Sscanf("1003450020170804890000000022344", "%4d%3d", &a, &b)
if err != nil {
   // ...
}

fmt.Println(a) // 1003
fmt.Println(b) // 450

Then you could create a structure with these.

答案2

得分: 1

一个解析函数很简单,可能已经足够了,而不需要声明辅助数据结构。

例如,可以按照以下方式编写:

func NewRecord(line string) (*Record, error) {

    if len(line) < 14 {
        return nil, fmt.Errorf("line is too short: %d", len(line))
    }

    return &Record{
        Id:   line[0:4],
        Name: line[4:14],
    }, nil
}
英文:

A parse function is simple and probably sufficient, rather than declaring ancillary data structures.

Eg, something along the lines of:

func NewRecord(line string) (*Record, error) {

	if len(line) &lt; 14 {
		return nil, fmt.Errorf(&quot;line is too short: %d&quot;, len(line))
	}

	return &amp;Record{
		Id:   line[0:4],
		Name: line[4:14],
	}, nil
}

huangapple
  • 本文由 发表于 2017年8月7日 10:23:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/45538573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定