Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:recycle: Reuse compiled constant regular expressions https://github.com/siyuan-note/siyuan/issues/20243

Danielab2a8bc9d425
diff --git a/kernel/api/icon.go b/kernel/api/icon.go
index ca07aea6f8..8d2ae96d1d 100644
--- a/kernel/api/icon.go
+++ b/kernel/api/icon.go
@@ -33,6 +33,8 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+var iconHanPattern = regexp.MustCompile(`[\p{Han}]`)
+
type ColorScheme struct {
Primary string
Secondary string
@@ -617,7 +619,7 @@ func generateTypeEightSVG(color, content string) string {
}
// 动态变化字体大小
- isChinese := regexp.MustCompile(`[\p{Han}]`).MatchString(content)
+ isChinese := iconHanPattern.MatchString(content)
var fontSize float64
if isChinese {
switch {
diff --git a/kernel/model/block.go b/kernel/model/block.go
index 845071ba1f..e34b2a541e 100644
--- a/kernel/model/block.go
+++ b/kernel/model/block.go
@@ -1430,16 +1430,16 @@ func filterEmbedBlocksByAccess(blocks []*sql.Block, accessChecker EmbedBlockAcce
return
}
+var (
+ embedHTMLPattern = regexp.MustCompile(`<div[^>]*data-type="NodeBlockQueryEmbed"[^>]*embed-content="[^"]*"[^>]*>`)
+ embedContentPattern = regexp.MustCompile(`embed-content="([^"]*)"`)
+)
+
func processEmbedHTML(htmlStr string) string {
// 使用正则表达式查找所有带有 embed-content 属性的嵌入块
- embedPattern := `<div[^>]*data-type="NodeBlockQueryEmbed"[^>]*embed-content="[^"]*"[^>]*>`
- re := regexp.MustCompile(embedPattern)
-
- return re.ReplaceAllStringFunc(htmlStr, func(match string) string {
+ return embedHTMLPattern.ReplaceAllStringFunc(htmlStr, func(match string) string {
// 提取 embed-content 属性值
- contentPattern := `embed-content="([^"]*)"`
- contentRe := regexp.MustCompile(contentPattern)
- contentMatches := contentRe.FindStringSubmatch(match)
+ contentMatches := embedContentPattern.FindStringSubmatch(match)
if len(contentMatches) > 1 {
embedContent := contentMatches[1]
@@ -1447,7 +1447,7 @@ func processEmbedHTML(htmlStr string) string {
embedContent = html.UnescapeString(embedContent)
// 移除 embed-content 属性,避免在最终 HTML 中显示
- cleanMatch := contentRe.ReplaceAllString(match, "")
+ cleanMatch := embedContentPattern.ReplaceAllString(match, "")
// 将内容插入到嵌入块内部
return cleanMatch + embedContent + "</div>"
diff --git a/kernel/model/cloud_service.go b/kernel/model/cloud_service.go
index 97c6462ee2..6c925e85c0 100644
--- a/kernel/model/cloud_service.go
+++ b/kernel/model/cloud_service.go
@@ -39,6 +39,12 @@ import (
var ErrFailedToConnectCloudServer = errors.New("failed to connect cloud server")
+var (
+ shorthandAudioPattern = regexp.MustCompile("<audio.*>.*</audio>")
+ shorthandVideoPattern = regexp.MustCompile("<video.*>.*</video>")
+ shorthandFilePattern = regexp.MustCompile("\\[文件]\\(.*\\)")
+)
+
func CloudChatGPT(msg string, contextMsgs []string) (ret string, stop bool, err error) {
user := Conf.GetUser()
if nil == user {
@@ -674,9 +680,6 @@ func GetCloudShorthands(page int) (result map[string]any, err error) {
}
luteEngine := NewLute()
- audioRegexp := regexp.MustCompile("<audio.*>.*</audio>")
- videoRegexp := regexp.MustCompile("<video.*>.*</video>")
- fileRegexp := regexp.MustCompile("\\[文件]\\(.*\\)")
shorthands := result["data"].(map[string]any)["shorthands"].([]any)
for _, item := range shorthands {
shorthand := item.(map[string]any)
@@ -686,9 +689,9 @@ func GetCloudShorthands(page int) (result map[string]any, err error) {
shorthand["hCreated"] = hCreated.Format("2006-01-02 15:04")
desc := shorthand["shorthandDesc"].(string)
- desc = audioRegexp.ReplaceAllString(desc, " 语音 ")
- desc = videoRegexp.ReplaceAllString(desc, " 视频 ")
- desc = fileRegexp.ReplaceAllString(desc, " 文件 ")
+ desc = shorthandAudioPattern.ReplaceAllString(desc, " 语音 ")
+ desc = shorthandVideoPattern.ReplaceAllString(desc, " 视频 ")
+ desc = shorthandFilePattern.ReplaceAllString(desc, " 文件 ")
desc = strings.ReplaceAll(desc, "\n\n", "")
desc = strings.TrimSpace(desc)
shorthand["shorthandDesc"] = desc
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 357500f2d0..fd49529c00 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -63,6 +63,12 @@ import (
_ "golang.org/x/image/webp"
)
+var (
+ importPrePattern = regexp.MustCompile(`(?sU)<pre [^>]*>(.*)</pre>`)
+ importSVGPattern = regexp.MustCompile(`(?i)<svg[^>]*>(.*?)</svg>`)
+ importEncodedNewlinePattern = regexp.MustCompile(`(?i)%0A`)
+)
+
// GetImportAssetsDir 返回导入资源的落盘目录。普通笔记本复用已有本地目录,否则回退到全局目录。
func GetImportAssetsDir(boxID, docDirLocalPath string) string {
globalAssetsDir := filepath.Join(util.DataDir, "assets")
@@ -115,7 +121,7 @@ func HTML2TreeWithOptions(htmlStr string, luteEngine *lute.Lute, boxID string,
case ast.NodeHTMLBlock:
if bytes.HasPrefix(n.Tokens, []byte("<pre ")) && bytes.HasSuffix(n.Tokens, []byte("</pre>")) {
if bytes.Contains(n.Tokens, []byte("data:image/svg+xml;base64")) {
- matches := regexp.MustCompile(`(?sU)<pre [^>]*>(.*)</pre>`).FindSubmatch(n.Tokens)
+ matches := importPrePattern.FindSubmatch(n.Tokens)
if len(matches) >= 2 {
n.Tokens = matches[1]
}
@@ -2032,8 +2038,7 @@ func htmlBlock2Media(tree *parse.Tree) {
}
func processHTMLBlockSvgImg(n *ast.Node, assetDirPath, boxID string) {
- re := regexp.MustCompile(`(?i)<svg[^>]*>(.*?)</svg>`)
- matches := re.FindStringSubmatch(string(n.Tokens))
+ matches := importSVGPattern.FindStringSubmatch(string(n.Tokens))
if 1 >= len(matches) {
return
}
@@ -2068,8 +2073,7 @@ func processBase64Img(n *ast.Node, dest string, assetDirPath, boxID string) {
}
typ = strings.ToLower(typ)
str := strings.TrimSpace(dest[sep+8:])
- re := regexp.MustCompile(`(?i)%0A`)
- str = re.ReplaceAllString(str, "\n")
+ str = importEncodedNewlinePattern.ReplaceAllString(str, "\n")
var decodeErr error
unbased, decodeErr := base64.StdEncoding.DecodeString(str)
if nil != decodeErr {
diff --git a/kernel/model/import_obsidian.go b/kernel/model/import_obsidian.go
index 7cad5b363c..3c5c58f9c3 100644
--- a/kernel/model/import_obsidian.go
+++ b/kernel/model/import_obsidian.go
@@ -234,10 +234,12 @@ var (
errObsidianVaultMarkdownMissing = errors.New("Obsidian Vault has no readable Markdown")
errObsidianSourceChanged = errors.New("Obsidian source file changed")
- obsidianBlockIDPattern = regexp.MustCompile(`(?m)(?:^|[ \t])\^([A-Za-z0-9-]+)[ \t]*$`)
- obsidianQuotePattern = regexp.MustCompile(`^((?:[ \t]*>[ \t]?)+)(.*)$`)
- obsidianListItemPattern = regexp.MustCompile(`^([ \t]*(?:[-+*]|\d+[.)])[ \t]+)(.*)$`)
- obsidianFootnotePattern = regexp.MustCompile(`(?m)\[\^[^\]\r\n]+\]`)
+ obsidianBlockIDPattern = regexp.MustCompile(`(?m)(?:^|[ \t])\^([A-Za-z0-9-]+)[ \t]*$`)
+ obsidianQuotePattern = regexp.MustCompile(`^((?:[ \t]*>[ \t]?)+)(.*)$`)
+ obsidianListItemPattern = regexp.MustCompile(`^([ \t]*(?:[-+*]|\d+[.)])[ \t]+)(.*)$`)
+ obsidianFootnotePattern = regexp.MustCompile(`(?m)\[\^[^\]\r\n]+\]`)
+ obsidianFootnoteDefinitionPattern = regexp.MustCompile(`(?m)^\[\^([^\]\r\n]+)\]:[ \t]*(.*?)[ \t]*\r?$`)
+ obsidianFootnoteReferencePattern = regexp.MustCompile(`\[\^([^\]\r\n]+)\]`)
)
func StartObsidianVaultAnalysis(localPath string) (*ObsidianVaultTask, error) {
@@ -2038,8 +2040,7 @@ func parseObsidianImageSize(value string) (width, height int, ok bool) {
func convertObsidianFootnotes(data []byte, stats *obsidianTransformStats) []byte {
scan := scanObsidianSource(data)
masked := maskObsidianProtected(data, scan.Protected)
- definitionPattern := regexp.MustCompile(`(?m)^\[\^([^\]\r\n]+)\]:[ \t]*(.*?)[ \t]*\r?$`)
- matches := definitionPattern.FindAllSubmatchIndex(masked, -1)
+ matches := obsidianFootnoteDefinitionPattern.FindAllSubmatchIndex(masked, -1)
if len(matches) == 0 {
return data
}
@@ -2058,8 +2059,7 @@ func convertObsidianFootnotes(data []byte, stats *obsidianTransformStats) []byte
definitions[label] = append(definitions[label], def)
orderedDefinitions = append(orderedDefinitions, def)
}
- refPattern := regexp.MustCompile(`\[\^([^\]\r\n]+)\]`)
- refMatches := refPattern.FindAllSubmatchIndex(masked, -1)
+ refMatches := obsidianFootnoteReferencePattern.FindAllSubmatchIndex(masked, -1)
var orderedLabels []string
seen := map[string]bool{}
for _, match := range refMatches {
diff --git a/kernel/model/render.go b/kernel/model/render.go
index 5fa4e2dd5d..f67d1d3141 100644
--- a/kernel/model/render.go
+++ b/kernel/model/render.go
@@ -35,6 +35,8 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+var outlineFontSizePattern = regexp.MustCompile("font-size:.*?;")
+
func renderOutline(heading *ast.Node, luteEngine *lute.Lute) (ret string) {
if nil == heading {
return ""
@@ -60,7 +62,7 @@ func renderOutline(heading *ast.Node, luteEngine *lute.Lute) (ret string) {
if style := n.IALAttr("style"); "" != style {
if strings.Contains(style, "font-size") { // 大纲字号不应该跟随字体设置 https://github.com/siyuan-note/siyuan/issues/7202
- style = regexp.MustCompile("font-size:.*?;").ReplaceAllString(style, "font-size: inherit;")
+ style = outlineFontSizePattern.ReplaceAllString(style, "font-size: inherit;")
n.SetIALAttr("style", style)
}
}
diff --git a/kernel/util/file.go b/kernel/util/file.go
index 61e996a5cc..b64910c46b 100644
--- a/kernel/util/file.go
+++ b/kernel/util/file.go
@@ -368,6 +368,8 @@ func FilterUploadFileName(name string) string {
return ret
}
+var pdfAnnoPngPattern = regexp.MustCompile("-{0,1}P{0,1}[0-9]{0,4}-{0,1}[0-9]{1,3}-[0-9]{14}-[0-9a-zA-Z]{7}\\.png$")
+
func TruncateLenFileName(name string) (ret string) {
// 插入资源文件时文件名长度最大限制 189 字节 https://github.com/siyuan-note/siyuan/issues/7099
ext := filepath.Ext(name)
@@ -381,9 +383,7 @@ func TruncateLenFileName(name string) (ret string) {
// PNG 图片可能是 PDF 标注的截图,包含页面和旋转角度(name--P1--270-id.png),所以允许的长度更短一些
// https://github.com/siyuan-note/siyuan/pull/16714#issuecomment-3737987302
- pdfAnnoPngPattern := "-{0,1}P{0,1}[0-9]{0,4}-{0,1}[0-9]{1,3}-[0-9]{14}-[0-9a-zA-Z]{7}\\.png$"
- regx := regexp.MustCompile(pdfAnnoPngPattern)
- pdfAnnoPngPart = regx.FindString(name)
+ pdfAnnoPngPart = pdfAnnoPngPattern.FindString(name)
if "" != pdfAnnoPngPart {
maxLen -= len(pdfAnnoPngPart) + len(".png")
name = strings.TrimSuffix(name, pdfAnnoPngPart)
diff --git a/kernel/util/misc.go b/kernel/util/misc.go
index 9737caba4d..baff792df6 100644
--- a/kernel/util/misc.go
+++ b/kernel/util/misc.go
@@ -66,14 +66,19 @@ func (o Optional[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(o.Value)
}
+var (
+ duplicateNamePattern = regexp.MustCompile(`^(.*) \((\d+)\)$`)
+ htmlCommentPattern = regexp.MustCompile(`<!--[\s\S]*?-->`)
+ htmlTagPattern = regexp.MustCompile(`<(/?)([a-zA-Z0-9]+)[^>]*?>`)
+)
+
func GetDuplicateName(master string) (ret string) {
if "" == master {
return
}
ret = master + " (1)"
- r := regexp.MustCompile(`^(.*) \((\d+)\)$`)
- m := r.FindStringSubmatch(master)
+ m := duplicateNamePattern.FindStringSubmatch(master)
if nil == m || 3 > len(m) {
return
}
@@ -150,16 +155,14 @@ func HasUnclosedHtmlTag(htmlStr string) bool {
}
// 去除所有注释内容
- commentRe := regexp.MustCompile(`<!--[\s\S]*?-->`)
- htmlStr = commentRe.ReplaceAllString(htmlStr, "")
+ htmlStr = htmlCommentPattern.ReplaceAllString(htmlStr, "")
- tagRe := regexp.MustCompile(`<(/?)([a-zA-Z0-9]+)[^>]*?>`)
selfClosing := map[string]bool{
"area": true, "base": true, "br": true, "col": true, "embed": true, "hr": true, "img": true,
"input": true, "link": true, "meta": true, "param": true, "source": true, "track": true, "wbr": true,
}
stack := []string{}
- matches := tagRe.FindAllStringSubmatch(htmlStr, -1)
+ matches := htmlTagPattern.FindAllStringSubmatch(htmlStr, -1)
for _, m := range matches {
isClose := m[1] == "/"
tag := strings.ToLower(m[2])