Fscanf and omitting fields like in C

WBOY
Release: 2024-02-12 16:18:05
forward
1110 people have browsed it

Fscanf 并像 C 中那样省略字段

Question content

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

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

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)
Copy after login

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
}
Copy after login
  • 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
    }
    
    Copy after login

    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!

    source:stackoverflow.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!