You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package util
import (
"regexp"
"strings"
"github.com/mizuki1412/go-core-kit/class/exception"
"golang.org/x/net/html"
)
func RegexpFindFirst ( content , regexpExpress string ) string {
//`"remandCode":"([^"]+)"`
//`"installNum":(\d+(\.\d+)?)`
// 定义正则表达式匹配
re := regexp . MustCompile ( regexpExpress )
// 在内容中查找匹配的字符串
match := re . FindStringSubmatch ( content )
if len ( match ) < 2 {
panic ( exception . New ( "regexp not found" ) )
}
// 第一个捕获组中的值即为要查找的
ok := match [ 1 ]
return ok
}
func HTMLContentFindFirst ( content , attrVal string ) string {
// 解析 HTML
doc , err := html . Parse ( strings . NewReader ( content ) )
if err != nil {
panic ( exception . New ( err . Error ( ) ) )
}
var res string
var find func ( * html . Node )
find = func ( n * html . Node ) {
if n . Type == html . ElementNode {
// 同时支持 input 和 textarea
if n . Data == "input" || n . Data == "textarea" {
// 匹配 name 属性
for _ , attr := range n . Attr {
if attr . Key == "name" && attr . Val == attrVal {
// 如果是 input, 取 value
if n . Data == "input" {
for _ , a := range n . Attr {
if a . Key == "value" {
res = a . Val
return
}
}
}
// 如果是 textarea, 取内部文本( 最关键! 你之前没写)
if n . Data == "textarea" && n . FirstChild != nil {
res = n . FirstChild . Data
return
}
}
}
}
}
// 递归子节点
for c := n . FirstChild ; c != nil ; c = c . NextSibling {
find ( c )
}
}
find ( doc )
return strings . TrimSpace ( res ) // 自动去空格换行
}