Golang Regexp.MatchString
最后修改于 2025 年 4 月 20 日
本教程将介绍如何在 Go 中使用 Regexp.MatchString 方法。我们将涵盖基本用法并提供实用的模式匹配示例。
一个 正则表达式 是一个定义搜索模式的字符序列。它用于在字符串中进行模式匹配。
Regexp.MatchString 方法报告一个已编译的正则表达式是否匹配一个字符串。如果找到匹配项,则返回 true。
基本 MatchString 示例
MatchString 最简单的用法是检查字符串是否包含某个模式。这里我们检查一个简单的单词匹配。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`hello`)
fmt.Println(re.MatchString("hello there")) // true
fmt.Println(re.MatchString("goodbye")) // false
fmt.Println(re.MatchString("HELLO")) // false
}
我们编译模式 "hello",并使用 MatchString 来测试字符串。该方法仅对精确的区分大小写的匹配返回 true。
不区分大小写的匹配
为了执行不区分大小写的匹配,我们可以修改我们的正则表达式。此示例演示了如何匹配而不考虑字母的大小写。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?i)hello`)
fmt.Println(re.MatchString("hello there")) // true
fmt.Println(re.MatchString("HELLO")) // true
fmt.Println(re.MatchString("hElLo")) // true
}
(?i) 标志使模式不区分大小写。这允许匹配任何大小写字母的变体。
匹配数字
MatchString 可以验证字符串是否包含数字模式。这里我们检查包含数字的字符串。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\d+`)
inputs := []string{"123", "abc", "45.67", "text123text"}
for _, input := range inputs {
if re.MatchString(input) {
fmt.Printf("'%s' contains numbers\n", input)
} else {
fmt.Printf("'%s' doesn't contain numbers\n", input)
}
}
}
模式 \d+ 匹配一个或多个数字。该方法对于包含至少一个数字的任何字符串都返回 true。
验证电子邮件格式
一个常见的用例是验证电子邮件格式。此示例展示了一个基本的电子邮件模式检查器。
package main
import (
"fmt"
"regexp"
)
func main() {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
re := regexp.MustCompile(pattern)
emails := []string{
"user@example.com",
"invalid.email",
"another.user@domain.co.uk",
}
for _, email := range emails {
if re.MatchString(email) {
fmt.Printf("%s is valid\n", email)
} else {
fmt.Printf("%s is invalid\n", email)
}
}
}
该模式匹配标准的电子邮件格式。请注意,完整的电子邮件验证需要更复杂的模式才能完全符合 RFC 标准。
检查特殊字符
我们可以使用 MatchString 来检查字符串是否包含特殊字符。此示例查找非字母数字字符。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`[^a-zA-Z0-9]`)
inputs := []string{"safeText", "text-with-dash", "text!with!exclamation"}
for _, input := range inputs {
if re.MatchString(input) {
fmt.Printf("'%s' contains special chars\n", input)
} else {
fmt.Printf("'%s' contains only alphanumeric\n", input)
}
}
}
模式 [^a-zA-Z0-9] 匹配任何不是字母或数字的字符。这有助于识别包含特殊字符的字符串。
匹配多个模式
我们可以组合模式来检查多个条件。此示例验证密码强度。
package main
import (
"fmt"
"regexp"
)
func main() {
hasUpper := regexp.MustCompile(`[A-Z]`)
hasLower := regexp.MustCompile(`[a-z]`)
hasNumber := regexp.MustCompile(`[0-9]`)
hasSpecial := regexp.MustCompile(`[^a-zA-Z0-9]`)
password := "SecurePass123!"
if !hasUpper.MatchString(password) {
fmt.Println("Password needs uppercase letters")
}
if !hasLower.MatchString(password) {
fmt.Println("Password needs lowercase letters")
}
if !hasNumber.MatchString(password) {
fmt.Println("Password needs numbers")
}
if !hasSpecial.MatchString(password) {
fmt.Println("Password needs special chars")
}
if len(password) < 8 {
fmt.Println("Password too short")
}
}
我们使用多个模式来检查不同的密码要求。每个条件都使用 MatchString 单独验证。
性能注意事项
重用已编译的模式可以提高性能。此示例演示了编译一次的好处。
package main
import (
"fmt"
"regexp"
"time"
)
func main() {
start := time.Now()
// Bad: Compiling in loop
for i := 0; i < 1000; i++ {
re, _ := regexp.Compile(`pattern`)
re.MatchString("test")
}
fmt.Println("Loop compile:", time.Since(start))
start = time.Now()
// Good: Compile once
re := regexp.MustCompile(`pattern`)
for i := 0; i < 1000; i++ {
re.MatchString("test")
}
fmt.Println("Single compile:", time.Since(start))
}
基准测试显示在循环外编译一次速度要快得多。为了获得更好的性能,请始终尽可能重用已编译的模式。
来源
本教程通过模式匹配和验证的实际示例,涵盖了 Go 中的 Regexp.MatchString 方法。