验证 HTML 字符串中的子字符串是否位于 Go 中的特定 HTML 标签内

问题描述 投票:0回答:1
html go
1个回答
0
投票

您可以使用正则表达式来完成此操作。

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
}
© www.soinside.com 2019 - 2024. All rights reserved.