如何将正则表达式应用于文件中的内容(Go)?

I'm using the io/ioutil package to read a file:

package main

import (
    "fmt"
    "github.com/codegangsta/cli"
    "io/ioutil"
    "os"
    "regexp"
)

func main() {
    app := cli.NewApp()
    app.Name = "m2k"
    app.Usage = "convert markdown to kindle"

    app.Action = func(c *cli.Context) {
        file := "no file"

        if len(c.Args().First()) > 0 {
            file = c.Args().First()

            fmt.Println("worked:", file)

            b, err := ioutil.ReadFile(file)
            if err != nil {
                panic(err)
            }

            r, _ := regexp.Compile(b)
            fmt.Println(r.ReplaceAllString("oldtext", "newtext"))
        }

    }

    app.Run(os.Args)
}

// $ go run io2.go input.txt

// input.txt

// text text oldtext oldtext

And I want to apply regex to the content of the file:

r, _ := regexp.Compile(b)
mt.Println(r.ReplaceAllString("oldtext", "newtext"))

The problem is that it seems like regexp.Compile doesn't work with the byte type:

./io2.go:29: cannot use b (type []byte) as type string in function argument

How can I solve this problem?

The regexp replace method returns the source argument with the regexp matches replaced by replacement argument. Because application is replacing "oldtext" with "newtext", "oldtext" is the regexp:

r, err := regexp.Compile("oldtext")

Because the application has the contents of the file as a []byte, ReplaceAll can be used insead of ReplaceAllString. This does require converting the replacment string to a []byte, but this is probably less expensive than converting the file to a string for ReplaceAllString.

r.ReplaceAll(b, []byte("newtext"))

The result of ReplaceAll is a []byte that can be written directly to stdout. There's no need to fmt.Println the output.

Here's the complete code:

b, err := ioutil.ReadFile(file)
if err != nil {
  panic(err)
}

r, err := regexp.Compile("oldtext")
if err != nil {
  // handle error
}
os.Stdout.Write(r.ReplaceAll(b, []byte("newtext")))

It seems you're trying to compile what your reading from the file into a regular expression.

The following syntax should correct your problem.

x := string(b)
r, err := regexp.Compile("oldtext")
if err != nil {
    return // problem with the regular expression.
}
fmt.Println(r.ReplaceAllString(x, "newtext"))

However, it's better to not convert binary data to strings and work directly with it.