Golang如何从含Token的HTML中提取关联UUID?
解决方案
是否需要正则表达式?
是的,正则表达式是处理这类结构化字符串提取的最优方案。相比手动切割字符串,正则能精准匹配Token的固定格式,一次性提取所需信息,代码更简洁可靠。
实现思路与步骤
- 匹配Token格式:用正则捕获
{{Token "..." .}}中引号内的完整Token字符串。 - 拆分Token与UUID:对捕获到的字符串按冒号拆分,判断是否包含标准UUID(长度固定36位)。
- 存入Map并检测:将Token名称和对应UUID存入
map[string]string,可通过strings.Contains快速检测HTML中是否存在目标Token,或直接判断Map键的存在性。
Go语言示例代码
package main import ( "fmt" "regexp" "strings" ) func main() { html := `<div style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);"><p style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);">Hello This is a friendly reminder about your upcoming appointment with </p><p style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);"><br></p><p style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);">Your appointment is: <span style="color: rgb(0, 0, 0);">{{Token "Stamps:appointmentDate" .}}</span>, <span style="color: rgb(0, 0, 0);">{{Token "Stamps:appointmentTime" .}}</span></p><p style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);"><br></p><p style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);">We appreciate your time and look forward to seeing you then!</p><p style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);"><br></p><p style="font-family: Arial; font-size: 16px; line-height: 1.4; margin: 0px; color: rgb(0, 0, 0);">Sincerely, <span style="color: rgb(0, 0, 0);">{{Token "Forms:emailAppointmentCancellation:0386DA88-B658-43E8-863C-296A22D732FF" .}}</span><br><br><br></div>` // 正则匹配{{Token "xxx" .}},捕获引号内的内容 re := regexp.MustCompile(`{{Token "([^"]+)" .}}`) matches := re.FindAllStringSubmatch(html, -1) tokenMap := make(map[string]string) for _, match := range matches { fullToken := match[1] parts := strings.Split(fullToken, ":") // 判断是否包含UUID(标准UUID长度为36位) if len(parts) >= 3 && len(parts[2]) == 36 { tokenName := parts[1] uuid := parts[2] tokenMap[tokenName] = uuid } else { // 无UUID的Token,可按需存入空值或忽略 tokenMap[parts[len(parts)-1]] = "" } } // 检测目标Token并输出结果 target := "emailAppointmentCancellation" if strings.Contains(html, target) { if uuid, ok := tokenMap[target]; ok { fmt.Printf("Token %s 对应的UUID:%s\n", target, uuid) } } else { fmt.Printf("Token %s 不存在\n", target) } // 输出所有提取的Token fmt.Println("\n所有提取结果:") for k, v := range tokenMap { fmt.Printf("%s: %s\n", k, v) } }
代码说明
- 正则表达式:
{{Token "([^"]+)" .}}精准匹配Token模板,([^"]+)捕获引号内的所有字符(直到下一个引号结束)。 - UUID判断:通过长度36位快速识别标准UUID,避免复杂格式校验。
- 存在性检测:先用
strings.Contains快速判断HTML中是否存在目标Token,再从Map中提取UUID,兼顾性能与准确性。
内容的提问来源于stack exchange,提问作者lily
相关产品推荐
相关产品推荐

