英文:
regexp value compared to string
问题
主要问题在于正则表达式的编写。你可以尝试使用以下代码来比较 addr
的值和正则表达式:
reg, _ := regexp.Compile(`internal`)
if err != nil {
println(err.Error())
return
}
if ip != "" {
validateIP(ip)
}
fmt.Println(x)
fmt.Println(addr[0])
if reg.MatchString(addr[0]) {
// 执行循环
// ...
}
这里使用了 MatchString
方法来检查 addr[0]
是否匹配正则表达式 internal
。如果匹配成功,则执行循环部分的代码。
希望这可以帮助到你!如果还有其他问题,请随时提问。
英文:
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.\n", addr)
fmt.Printf("Remote Address : %s \n", conn.RemoteAddr().String())
fmt.Printf("Local Address : %s \n", 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
得分: 1
你可以使用Regexp.MatchString方法来实现你想要的功能。
if re.MatchString(addr[0]) {
// ...
}
在文档中有很多示例,你可以查看一下:https://golang.org/pkg/regexp/#pkg-examples
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论