Golang如何从HTML内容中清除字符串

Golang如何从HTML内容中清除字符串 有一个字符串,例如

s := "<b>John</b> Thank you."

清理字符串中

"<b>...</b>"

内容的最佳方法是什么?

4 回复

我的理解是您想要获取 <b> 标签的内容吗?但我希望得到的结果是将源字符串转换为:

谢谢。

更多关于Golang如何从HTML内容中清除字符串的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


对于Python有广泛使用的Beautiful Soup

对于Go语言,有一个移植版本叫做soup。其中的Text方法正是你所需要的。

GitHub头像

anaskhan96/soup

Go语言中的网页抓取工具,类似于BeautifulSoup。通过在GitHub上创建账户来为anaskhan96/soup开发做贡献。

请查看这个正则表达式

package main

import (
	"fmt"
	"regexp"
)

const sample = `<b>John</b>Thank you.<b>delete this</b>`

func main() {
	var re = regexp.MustCompile(`<(b|B)>\b(([^<])*|(<[^b])*|(<b[^>])*)\b</(b|B)>`)
	s := re.ReplaceAllString(sample, ``)
	fmt.Println(s)
}

在Go语言中,要从HTML内容中清除特定标签(如<b>...</b>),可以使用标准库中的regexp包进行正则表达式匹配和替换。以下是一个示例实现:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := "<b>John</b> Thank you."
    
    // 编译正则表达式匹配<b>标签及其内容
    re := regexp.MustCompile(`<b>.*?</b>`)
    
    // 替换所有匹配的<b>标签为空字符串
    cleaned := re.ReplaceAllString(s, "")
    
    fmt.Println("原始字符串:", s)
    fmt.Println("清理后字符串:", cleaned)
}

输出结果:

原始字符串: <b>John</b> Thank you.
清理后字符串:  Thank you.

如果需要更精确地处理嵌套标签或复杂HTML结构,可以考虑使用golang.org/x/net/html包进行解析:

package main

import (
    "bytes"
    "fmt"
    "strings"
    
    "golang.org/x/net/html"
)

func removeBTags(htmlStr string) (string, error) {
    doc, err := html.Parse(strings.NewReader(htmlStr))
    if err != nil {
        return "", err
    }
    
    var removeNodes []*html.Node
    var f func(*html.Node)
    f = func(n *html.Node) {
        if n.Type == html.ElementNode && n.Data == "b" {
            removeNodes = append(removeNodes, n)
        }
        for c := n.FirstChild; c != nil; c = c.NextSibling {
            f(c)
        }
    }
    f(doc)
    
    for _, node := range removeNodes {
        if node.Parent != nil {
            node.Parent.RemoveChild(node)
        }
    }
    
    var buf bytes.Buffer
    if err := html.Render(&buf, doc); err != nil {
        return "", err
    }
    
    return buf.String(), nil
}

func main() {
    s := "<b>John</b> Thank you."
    cleaned, err := removeBTags(s)
    if err != nil {
        fmt.Println("错误:", err)
        return
    }
    
    fmt.Println("原始字符串:", s)
    fmt.Println("清理后字符串:", cleaned)
}

第一种方法适用于简单的标签清除,第二种方法通过HTML解析器能更可靠地处理复杂的HTML结构。

回到顶部