Home >Backend Development >Golang >Fscanf and omitting fields like in C

Fscanf and omitting fields like in C

WBOY
WBOYforward
2024-02-12 16:18:051179browse

Fscanf 并像 C 中那样省略字段

Question content

Is it possible to omit the field %*s like in C?

var pid int
fmt.Fscanf(r, "%*s %d", &pid)

Workaround

Actually, you can't do this in Go (at least on Go 1.21.0).

Source code shows:

  • There are no verbs with omitted fields in the format string (like %*s in C): in fact, the verb of a string is always a single character (% s, %v, %q, %X or %X)
  • Fscanf Method Iteration Parameters (Fscanf array in a(r io.Reader , format string, a...any)). Therefore, you mustdefine a parameter in a even if you don't care about its value

If you don’t want to define variables, you can use:

var pid int
fmt.Fscanf(r, "%s %d", new(string), &pid)

Other alternatives

For your specific case, to parse something in the reader, you can first read the reader into a string (e.g. io.ReadAll):

CB835C294C06824721603abd255bd78a

Then use the strings.Split method or regular expression, for example:

  1. and strings.Split
pidString := strings.Split(string(s), " ")[1]
pid, err := strconv.Atoi(pidString)
if err != nil {
    panic(err) // handle the error
}
  1. Use regular expressions:
re := regexp.MustCompile(`[^\s]+ (?P<pid>\d+)`) // similar to "%s %d"
matches := re.FindStringSubmatch(s)
pidString := matches[re.SubexpIndex("pid")]
pid, err := strconv.Atoi(pidString)
if err != nil {
    panic(err) // handle the error
}

There may be other methods, but these should suffice. Hope that helps.

The above is the detailed content of Fscanf and omitting fields like in C. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete