Is it possible to omit the field %*s
like in C?
var pid int fmt.Fscanf(r, "%*s %d", &pid)
Actually, you can't do this in Go (at least on Go 1.21.0).
Source code shows:
%*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 valueIf you don’t want to define variables, you can use:
var pid int fmt.Fscanf(r, "%s %d", new(string), &pid)
For your specific case, to parse something in the reader, you can first read the reader into a string (e.g. io.ReadAll
):
Then use the strings.Split
method or regular expression, for example:
strings.Split
pidString := strings.Split(string(s), " ")[1] pid, err := strconv.Atoi(pidString) if err != nil { panic(err) // handle the error }
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!