您可以使用正则表达式来完成此操作。
func betweenValidTags(input string, subStr string) bool {
// regex for tags <p>, <li>, <h2>
inTags := fmt.Sprintf(`<(p|li|h2)[^>]*>.*?%s.*?</\1>`, regexp.QuoteMeta(subStr))
re := regexp.MustCompile(inTags)
return re.MatchString(input)
}
这很容易理解,但动态编译正则表达式的成本很高。
如果您大量使用此函数,另一种方法是创建可重用的正则表达式并手动检查匹配项。
var tagRegex = regexp.MustCompile(`<(p|li|h2)[^>]*>(.*?)</\1>`)
func betweenValidTags(input string, subStr string) bool {
matches := tagRegex.FindAllStringSubmatch(input, -1)
// Iterate through all matches and check if subStr is within the matched content
for _, match := range matches {
if len(match) > 2 && match[2] == subStr {
return true
}
}
return false
}