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

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探