Files
bulma/regexp/regexp_demo_6_1.go
T

183 lines
7.3 KiB
Go

package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
fmt.Println("=== Golang正则表达式ReplaceAllLiteralString使用示例 ===")
// 1. 基本用法演示
fmt.Println("\n1. 基本用法演示")
text := "Hello world! This is a world of Go programming. Welcome to the world!"
// 使用普通替换
normalReplace := regexp.MustCompile(`world`).ReplaceAllString(text, "universe")
fmt.Printf("原始文本: %s\n", text)
fmt.Printf("普通替换(ReplaceAllString): %s\n", normalReplace)
// 使用字面量替换
literalReplace := regexp.MustCompile(`world`).ReplaceAllLiteralString(text, "universe")
fmt.Printf("字面量替换(ReplaceAllLiteralString): %s\n", literalReplace)
// 2. 特殊字符处理对比
fmt.Println("\n2. 特殊字符处理对比")
specialText := "Price: $100, Discount: $20, Total: $80"
// 普通替换 - $有特殊含义
normalResult := regexp.MustCompile(`\$`).ReplaceAllString(specialText, "USD ")
fmt.Printf("特殊字符 - 普通替换: %s\n", normalResult)
// 字面量替换 - $被视为普通字符
literalResult := regexp.MustCompile(`\$`).ReplaceAllLiteralString(specialText, "USD ")
fmt.Printf("特殊字符 - 字面量替换: %s\n", literalResult)
// 3. 捕获组符号处理
fmt.Println("\n3. 捕获组符号处理")
groupText := "Pattern: (abc) and [def] with {ghi}"
// 普通替换 - $1, $2等会被当作捕获组引用
normalGroup := regexp.MustCompile(`\(([^\)]+)\)`).ReplaceAllString(groupText, "GROUP($1)")
fmt.Printf("捕获组 - 普通替换: %s\n", normalGroup)
// 字面量替换 - $符号被当作普通字符处理
literalGroup := regexp.MustCompile(`\(([^\)]+)\)`).ReplaceAllLiteralString(groupText, "GROUP($1)")
fmt.Printf("捕获组 - 字面量替换: %s\n", literalGroup)
// 4. 实际应用场景 - HTML转义
fmt.Println("\n4. 实际应用场景 - HTML转义")
htmlText := "<div class='test'>Click & go to \"page\"</div>"
// 正确的HTML转义方法 - 使用ReplaceAllStringFunc
htmlReplacer := regexp.MustCompile(`[<>&"']`)
escapedHTML := htmlReplacer.ReplaceAllStringFunc(htmlText, func(match string) string {
switch match {
case "<":
return "&lt;"
case ">":
return "&gt;"
case "&":
return "&amp;"
case "\"":
return "&quot;"
case "'":
return "&#x27;"
default:
return match
}
})
fmt.Printf("HTML转义前: %s\n", htmlText)
fmt.Printf("HTML转义后: %s\n", escapedHTML)
// 5. SQL注入防护
fmt.Println("\n5. SQL注入防护示例")
sqlText := "SELECT * FROM users WHERE name = 'admin'; DROP TABLE users; --'"
// 移除危险字符 - 使用ReplaceAllLiteralString
sqlSafe := regexp.MustCompile(`['";--]`).ReplaceAllLiteralString(sqlText, "_")
fmt.Printf("原始SQL: %s\n", sqlText)
fmt.Printf("净化后SQL: %s\n", sqlSafe)
// 6. 路径规范化
fmt.Println("\n6. 路径规范化")
pathText := "/home/user/../documents/./files//temp/"
// 标准化路径分隔符
normalizedPath := regexp.MustCompile(`/+`).ReplaceAllLiteralString(pathText, "/")
fmt.Printf("原始路径: %s\n", pathText)
fmt.Printf("标准化路径: %s\n", normalizedPath)
// 7. 用户输入清理
fmt.Println("\n7. 用户输入清理")
userInput := "User input with <script>alert('xss')</script> and other dangerous content"
// 移除潜在危险标签
cleanInput := regexp.MustCompile(`<script[^>]*>.*?</script>`).ReplaceAllLiteralString(userInput, "")
fmt.Printf("原始输入: %s\n", userInput)
fmt.Printf("清理后输入: %s\n", cleanInput)
// 8. 电话号码格式化
fmt.Println("\n8. 电话号码格式化")
phoneText := "Call me at 1234567890 or 0987654321 for more info"
// 正确的格式化方法 - 使用ReplaceAllString(因为需要捕获组引用)
correctFormattedPhone := regexp.MustCompile(`(\d{3})(\d{3})(\d{4})`).ReplaceAllString(phoneText, "$1-$2-$3")
fmt.Printf("原始号码: %s\n", phoneText)
fmt.Printf("格式化号码: %s\n", correctFormattedPhone)
// 9. 敏感信息脱敏
fmt.Println("\n9. 敏感信息脱敏")
sensitiveText := "Email: john@example.com, Phone: 123-456-7890, SSN: 123-45-6789"
// 脱敏邮箱 - 使用ReplaceAllString(需要捕获组)
emailMasked := regexp.MustCompile(`([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})`).ReplaceAllString(sensitiveText, "***@***.com")
fmt.Printf("原始信息: %s\n", sensitiveText)
fmt.Printf("邮箱脱敏: %s\n", emailMasked)
// 10. 关键词过滤
fmt.Println("\n10. 关键词过滤")
badWordsText := "This contains some bad words like crap, damn, and hell that should be filtered out"
// 过滤不良词汇
filteredText := regexp.MustCompile(`(?i)(crap|damn|hell)`).ReplaceAllLiteralString(badWordsText, "***")
fmt.Printf("原文本: %s\n", badWordsText)
fmt.Printf("过滤后: %s\n", filteredText)
// 11. 价格格式化
fmt.Println("\n11. 价格格式化")
priceText := "Product A costs $29.99, Product B costs $199.99"
// 将美元符号替换为人民币符号 - 使用ReplaceAllLiteralString
rmbPrice := regexp.MustCompile(`\$`).ReplaceAllLiteralString(priceText, "¥")
fmt.Printf("原始价格: %s\n", priceText)
fmt.Printf("人民币价格: %s\n", rmbPrice)
// 12. 批量替换示例
fmt.Println("\n12. 批量替换示例")
batchText := "Replace @user with [USERNAME] and #hashtag with [HASHTAG]"
// 替换多个模式
result := batchText
result = regexp.MustCompile(`@(\w+)`).ReplaceAllLiteralString(result, "[USER]")
result = regexp.MustCompile(`#(\w+)`).ReplaceAllLiteralString(result, "[TAG]")
fmt.Printf("原始文本: %s\n", batchText)
fmt.Printf("批量替换后: %s\n", result)
// 13. 特殊字符处理
fmt.Println("\n13. 特殊字符处理")
specialCharsText := "This has special chars: $10, \\path, $variable, and \\n newlines"
// 处理包含$和\的文本 - 使用ReplaceAllLiteralString确保特殊字符被正确处理
safeReplace := regexp.MustCompile(`special chars: \$10, \\path`).ReplaceAllLiteralString(specialCharsText, "SAFE TEXT")
fmt.Printf("原始文本: %s\n", specialCharsText)
fmt.Printf("安全替换后: %s\n", safeReplace)
// 14. 性能对比演示
fmt.Println("\n14. 性能对比演示")
longText := strings.Repeat("This is a test string with pattern to replace. ", 1000)
// 测试ReplaceAllLiteralString性能
re1 := regexp.MustCompile(`pattern`)
// 由于无法直接测试性能,这里展示用法
literalResult = re1.ReplaceAllLiteralString(longText, "replacement")
fmt.Printf("ReplaceAllLiteralString处理长文本完成,结果长度: %d\n", len(literalResult))
// 15. 实际应用:日志清理
fmt.Println("\n15. 实际应用:日志清理")
logText := "INFO: User login success for admin@company.com at 2026-06-15 10:30:45"
// 清理敏感信息
cleanLog := regexp.MustCompile(`\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b`).ReplaceAllLiteralString(logText, "[EMAIL_REDACTED]")
fmt.Printf("原始日志: %s\n", logText)
fmt.Printf("清理后日志: %s\n", cleanLog)
fmt.Println("\n=== ReplaceAllLiteralString vs ReplaceAllString 对比 ===")
fmt.Println("ReplaceAllString: 替换字符串中的$符号有特殊含义,用于引用捕获组")
fmt.Println("ReplaceAllLiteralString: 替换字符串中的$符号被当作普通字符处理,不会被解释为捕获组引用")
fmt.Println("使用场景: 当替换字符串包含$、\\等特殊字符且不想被解释时,使用ReplaceAllLiteralString")
fmt.Println("\n注意: 如果需要使用捕获组功能,应使用ReplaceAllString或ReplaceAllStringFunc")
}