duanang58939 2017-04-12 18:38
浏览 30
已采纳

正则表达式值与字符串相比

func main() {

    var ip string
    fmt.Print("Host: ")
    fmt.Scanln(&ip)

    addr, _ := net.LookupAddr(ip)

    app := "grep"
    arg0 := "inst"
    arg1 := "acl.yaml"

    cmd := exec.Command(app, arg0, arg1)
    stdout, err := cmd.Output()
    x := string(stdout)

    reg, _ := regexp.Compile(`(internal)`)
    if err != nil {
        println(err.Error())
        return
    }
    if ip != "" {
        validateIP(ip)
    }
    fmt.Println(x)
    fmt.Println(addr[0])
    //fmt.Println(stdout)
    if addr[0] == reg.FindString(`(internal)`){
        file, err := os.Open("ports.json")
        if err != nil {
            panic(err)
        }
        defer file.Close()
        ports := []portDef{}
        err = json.NewDecoder(file).Decode(&ports)
        if err != nil {
            panic(err)
        }

        for _, p := range ports {
            conn, err := net.Dial(p.Protocol, ip + ":" + p.Port)
            if conn != nil {
                fmt.Println("")
                fmt.Printf("Connection established between %s and Localhost.
", addr)
                fmt.Printf("Remote Address : %s 
", conn.RemoteAddr().String())
                fmt.Printf("Local Address : %s 
", conn.LocalAddr().String())
            }
            fmt.Println("")
            if err != nil {
                fmt.Println(err)
            }
        }
    }
}

I am trying to compare a regexp value to a string. In this case I want the value of "addr" to be compared to the regex and if the value of addr has "internal" in it that it opens the selected file and iterates through the ports. The address returned from the LookupAddr is always in box.internal.blah.blah.com, so I am looking for the second field in the address (internal in this case) to be compared to the regex and if it finds "internal" in the address it will cycle through the loop.

I know my regexp is most likely what is wrong here. Any help would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • doukunsan5553 2017-04-12 18:57
    关注

    You can use the Regexp.MatchString method to do what you want.

    if re.MatchString(addr[0]) {
        // ...
    }
    

    https://play.golang.org/p/UvB16idiyf

    There are quite a few examples in the docs, check them out: https://golang.org/pkg/regexp/#pkg-examples

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器