← 中文资源

简体中文版本

QuoteMeta 转义字面匹配

用户输入进正则前先 regexp.QuoteMeta:点号星号等元字符被转义成字面量,未转义时 a.b 会误命中 aXb。

阅读英文原文

实现说明

真正干活的是函数 unsafeMatch、safeMatch、main、count,其余都是接线。 迭代发生在 for _, word := range regexp.MustCompile(" ").Split(text, -1) 内部——循环之外的语句只执行一遍。

使用要点

  • 跑完文件,输出里会留下标记——unsafe count:、safe count:、quoted pattern:。
  • 运行整个文件:main 会依次驱动 count。

常见问题

运行「QuoteMeta 转义字面匹配」会打印什么?

整个文件跑完,输出行以 unsafe count:、safe count:、quoted pattern: 这类前缀开头。

主要签名是 func unsafeMatch(input, text string) bool

核心语句

func count(input, text string, matcher func(string, string) bool) int {
	total := 0
	for _, word := range regexp.MustCompile(" ").Split(text, -1) {
		if matcher(input, word) {
			total++
		}
	}
	return total
}
func unsafeMatch(input, text string) bool {
	re := regexp.MustCompile(input) // "a.b" 变成"任意字符分隔的 a b"
	return re.MatchString(text)
}
func safeMatch(input, text string) bool {
	re := regexp.MustCompile(regexp.QuoteMeta(input))
	return re.MatchString(text)
}

代码示例

package main

import (
	"fmt"
	"regexp"
)

// 用用户输入直接拼正则:元字符改变模式语义
func unsafeMatch(input, text string) bool {
	re := regexp.MustCompile(input) // "a.b" 变成"任意字符分隔的 a b"
	return re.MatchString(text)
}

// QuoteMeta 把每个元字符转义成字面量:输入只匹配它自己
func safeMatch(input, text string) bool {
	re := regexp.MustCompile(regexp.QuoteMeta(input))
	return re.MatchString(text)
}

func main() {
	needle := "a.b"
	text := "a.b aXb"

	// 未转义:"a.b" 同时命中 a.b 和 aXb
	fmt.Println("unsafe count:", count(needle, text, unsafeMatch))

	// QuoteMeta 后只命中字面 a.b
	fmt.Println("safe count:", count(needle, text, safeMatch))

	fmt.Println("quoted pattern:", regexp.QuoteMeta("1+1=2 (x*?)"))
}

func count(input, text string, matcher func(string, string) bool) int {
	total := 0
	for _, word := range regexp.MustCompile(" ").Split(text, -1) {
		if matcher(input, word) {
			total++
		}
	}
	return total
}