dongmou1964 2017-09-13 02:08
浏览 79
已采纳

golang exec find命令正则表达式[重复]

This question already has an answer here:

I am trying to write a find command (shell command below) in go:

find . -mindepth 3 -maxdepth 3 -regex '.*\(type-a\|type-b\)\/os.*'

Here is the go snippet:

package main

import (
    "bytes"
    "fmt"
    "os/exec"
)

func main() {

    cmd := exec.Command("/usr/bin/find", "/opt/system/versions",
                        "-mindepth",  "3", "-maxdepth",  "3",
                        "-regex",  ".*(type-a|type-b)/os.*")

    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr

    err:= cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return
    }
    fmt.Println("Directory contents : ", out.String())
}

It works fine if I search for just type-a (or just type-b). Does not work when I search for either type-a or type-b (the shell command works just fine). What did I get wrong in the regex pattern fed into Command?

When I escape the (, | and ) using \ , go complains about the escape sequence - unknown escape sequence: (:

    cmd := exec.Command("/usr/bin/find", "/opt/system/versions",
                        "-mindepth",  "3", "-maxdepth",  "3",
                        "-regex",  ".*\(type-a\|type-b\)/os.*")
</div>
  • 写回答

1条回答 默认 最新

  • douqianmin5367 2017-09-13 02:36
    关注

    By default, find interprets regular expressions as Emacs Regular Expressions, where, particularly, the alteration operator is \|, and grouping is performed with backslashes followed by parentheses \(, \). So you should either use the correct Emacs Regular Expressions syntax, or use alternative regular expressions syntax with the help of -regextype option, where these operators are not prefixed with backslashes, e.g.:

    find -regextype 'posix-extended' -regex '.*(type-a|type-b)/os.*'
    

    Since backslash in Go is used as an escape character in strings, you should escape the backslash character itself with an extra backslash, e.g.:

    cmd := exec.Command("/usr/bin/find", "/opt/system/versions",
                        "-mindepth",  "3", "-maxdepth",  "3",
                        "-regex",  ".*\\(type-a\\|type-b\\)\\/os.*")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题