Case insensitive string search in golang

后端 未结 4 1117
清歌不尽
清歌不尽 2020-12-24 13:09

How do I search through a file for a word in a case insensitive manner?

For example

If I\'m searching for UpdaTe in

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 13:33

    If your file is large, you can use regexp and bufio:

    //create a regex `(?i)update` will match string contains "update" case insensitive
    reg := regexp.MustCompile("(?i)update")
    f, err := os.Open("test.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    
    //Do the match operation
    //MatchReader function will scan entire file byte by byte until find the match
    //use bufio here avoid load enter file into memory
    println(reg.MatchReader(bufio.NewReader(f)))
    

    About bufio

    The bufio package implements a buffered reader that may be useful both for its efficiency with many small reads and because of the additional reading methods it provides.

提交回复
热议问题