Regexp QuoteMeta Literal Match

Escape user-supplied text with regexp.QuoteMeta before building patterns, so dots and stars in input match themselves instead of rewriting the search.

GoSecurity Boundaries

Code

gosnippet
41 lines
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
}

How it works

Regexp QuoteMeta Literal Match comes down to the functions unsafeMatch, safeMatch, main and count.

A single loop drives the file — for _, word := range regexp.MustCompile(" ").Split(text, -1).

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func unsafeMatch(input, text string) bool

Running the file prints labeled results such as unsafe count:, safe count:, quoted pattern: — each operation’s effect is visible in the output.

Running the file executes main, which drives count in order.

Key statements

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)
}

Interactive Tools for This Topic

FAQ

What does Regexp QuoteMeta Literal Match print when run?
No setup needed: run the file and look for labeled lines like `unsafe count:`, `safe count:`, `quoted pattern:` in the output.