我做了这个正则表达式来捕获所有类型的url
(它实际上捕获了所有url
),但它也捕获了单个ip
。
这是我的情况:我有一个完整的IP,哈希和url列表,我的url regex和ip regex都捕获了相同的条目。我不知道单个IP是否可以视为“URL”。
我的正则表达式:((http|https)://)?(www)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,9}\b([-a-zA-Z0-9()@:%_\|+.~#?&//={};,\[\]'"$\x60]*)?
捕获所有这些:
http://127.0.0.1/
http://127.0.0.1
https://127.0.0.1/m=weblogin/loginform238,363,771,89816356,2167
127.0.0.1:8080 ------> excluding this one is okay too (optional)
127.0.0.1 ------> i want to exclude this one
google.com
google.com:80
www.google.com
https://google.com
https://www.google.com
我希望我的正则表达式捕获像单个ip这样的所有URL,如下所示:127.0.0.1
regexp.Compile()
和FindAllString
函数。 try this regex on regex101
最佳答案
您可以使用正则表达式和"best trick ever"来实现 FindAllStringSubmatch
:匹配您需要跳过/忽略的内容,匹配并捕获您需要保留的内容。
\b(?:https?://)?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b(?:[^:]|$)|((?:https?://)?(?:www)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,9}\b[-a-zA-Z0-9()@:%_\|+.~#?&//={};,\[\]'"$\x60]*)
第一种选择是IP matching regex,我在其中添加了(?:https?://)?
部分以匹配可选协议(protocol)部分和(?:[^:]|$)
部分,以确保IP模式之后紧跟:
或字符串末尾之外的其他字符,但是您可以进一步调整此部分。然后,use it in Go喜欢
package main
import (
"fmt"
"regexp"
)
func main() {
r := regexp.MustCompile(`\b(?:https?://)?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b(?:[^:]|$)|((?:https?://)?(?:www)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,9}\b[-a-zA-Z0-9()@:%_\|+.~#?&//={};,\[\]'"$\x60]*)`)
matches := r.FindAllStringSubmatch(`http://127.0.0.1/
http://127.0.0.1
http://www.127.0.0.1/m=weblogin/loginform238,363,771,89816356,2167
127.0.0.1:8080
127.0.0.1
google.com
google.com:80
www.google.com
https://google.com
https://www.google.com`, -1)
for _, v := range matches {
if (len(v[1]) > 0) { // if Group 1 matched
fmt.Println(v[1]) // Display it, else do nothing
}
}
}
输出:http://www.127.0.0.1/m=weblogin/loginform238,363,771,89816356,2167
127.0.0.1:8080
google.com
google.com:80
www.google.com
https://google.com
https://www.google.com