Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从ruby到go的移植:在文件中查找和替换_Ruby_Go - Fatal编程技术网

从ruby到go的移植:在文件中查找和替换

从ruby到go的移植:在文件中查找和替换,ruby,go,Ruby,Go,我正在向golang移植一些ruby代码。我很难为下面这行找到一个好的等价物,我想知道是否有人知道比我下面的更好的解决方案。基本前提是在文件中找到一行有很多空格的行并删除该行 我还想过使用exec调用sed-I,但当我尝试时,它没有起作用,下面的代码终于起作用了 红宝石: 戈兰: b, err := ioutil.ReadFile(filename) if err != nil { return } // I happen to know that there will be at l

我正在向golang移植一些ruby代码。我很难为下面这行找到一个好的等价物,我想知道是否有人知道比我下面的更好的解决方案。基本前提是在文件中找到一行有很多空格的行并删除该行

我还想过使用exec调用sed-I,但当我尝试时,它没有起作用,下面的代码终于起作用了

红宝石:

戈兰:

b, err := ioutil.ReadFile(filename)
if err != nil {
    return
}

// I happen to know that there will be at least 30 spaces,
// but I would really prefer to not use a hardcoded value here.
// I was just never able to make using '^\s*$' work in the regex.

r := regexp.MustCompile(`[ ]{30,}`)  // there's a space in the []
newb := r.ReplaceAll(b, []byte(""))
err = ioutil.WriteFile(filename, newb, 0666)
if err != nil {
    fmt.Printf("Unable to write to file (%+v)\n", err)
    return
}

启用多行模式,您的原始图案将正常工作:

r := regexp.MustCompile(`(?m)^\s*$`)
使用字符串演示:

@KVS7是描述Go支持的REs语法的文档。
r := regexp.MustCompile(`(?m)^\s*$`)