A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
refactor(internal): compile regex once while clearing text
ferhat elmas9b64d7d64d58
diff --git a/pkg/htmltext/htmltext.go b/pkg/htmltext/htmltext.goindex 49049109..0b84cda4 100644--- a/pkg/htmltext/htmltext.go+++ b/pkg/htmltext/htmltext.go@@ -34,38 +34,34 @@ import ("github.com/mozillazg/go-pinyin")+var (+ reCode = regexp.MustCompile(`(?ism)<(pre)>.*<\/pre>`)+ reCodeReplace = "{code...}"+ reLink = regexp.MustCompile(`(?ism)<a.*?[^<]>(.*)?<\/a>`)+ reLinkReplace = " [$1] "+ reSpace = regexp.MustCompile(` +`)+ reSpaceReplace = " "++ spaceReplacer = strings.NewReplacer(+ "\n", " ",+ "\r", " ",+ "\t", " ",+ )+)+// ClearText clear HTML, get the clear text-func ClearText(html string) (text string) {- if len(html) == 0 {- text = html- return+func ClearText(html string) string {+ if html == "" {+ return html}- var (- re *regexp.Regexp- codeReg = `(?ism)<(pre)>.*<\/pre>`- codeRepl = "{code...}"- linkReg = `(?ism)<a.*?[^<]>(.*)?<\/a>`- linkRepl = " [$1] "- spaceReg = ` +`- spaceRepl = " "- )- re = regexp.MustCompile(codeReg)- html = re.ReplaceAllString(html, codeRepl)+ html = reCode.ReplaceAllString(html, reCodeReplace)+ html = reLink.ReplaceAllString(html, reLinkReplace)- re = regexp.MustCompile(linkReg)- html = re.ReplaceAllString(html, linkRepl)-- text = strings.NewReplacer(- "\n", " ",- "\r", " ",- "\t", " ",- ).Replace(strip.StripTags(html))+ text := spaceReplacer.Replace(strip.StripTags(html))// replace multiple spaces to one space- re = regexp.MustCompile(spaceReg)- text = strings.TrimSpace(re.ReplaceAllString(text, spaceRepl))- return+ return strings.TrimSpace(reSpace.ReplaceAllString(text, reSpaceReplace))}func UrlTitle(title string) (text string) {