Files
bulma/regexp/regexp_demo_6.go
T

58 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"regexp"
"strconv"
)
func main() {
// 1、字符串反向引用脱敏 ReplaceAllString
mobileRe := regexp.MustCompile(`(\d{3})\d{4}(\d{4})`)
phone := "12311111111"
// $$ 转义输出单个字面$
res1 := mobileRe.ReplaceAllString(phone, "前缀$$ $1****$2 后缀")
fmt.Println("1.ReplaceAllString 手机号脱敏+$转义:", res1)
// 命名捕获组搭配${name}格式
nameRe := regexp.MustCompile(`姓名:(?P<name>[\p{Han}]+)`)
userText := "姓名:王五"
resName := nameRe.ReplaceAllString(userText, "用户${name}已登记")
fmt.Println("命名捕获组替换:", resName)
// 2、字面量&常规替换核心对比(带捕获组,差异肉眼可见)
litStr := "价格$100,优惠$20"
numRe := regexp.MustCompile(`(\d+)`)
res2Normal := numRe.ReplaceAllString(litStr, "数值$1")
res2Lit := numRe.ReplaceAllLiteralString(litStr, "数值$1")
fmt.Println("2.ReplaceAllString 解析捕获组$1", res2Normal)
fmt.Println("2.ReplaceAllLiteralString 纯字面$1", res2Lit)
// 3、动态回调替换 ReplaceAllStringFunc
priceText := "金额:10、20、50"
res3 := numRe.ReplaceAllStringFunc(priceText, func(s string) string {
val, _ := strconv.Atoi(s)
return strconv.Itoa(val * 2)
})
fmt.Println("3.ReplaceAllStringFunc 数值翻倍:", res3)
// ---------------------- []byte 字节系列替换API ----------------------
bytePhone := []byte("12311111111")
// 4.ReplaceAll 字节版反向引用
resByte1 := mobileRe.ReplaceAll(bytePhone, []byte("$1****$2"))
fmt.Println("4.ReplaceAll 字节脱敏:", string(resByte1))
// 5.ReplaceAllLiteral 字节字面量演示
byteSrc := []byte("积分30")
resByte2 := numRe.ReplaceAllLiteral(byteSrc, []byte("分数$1"))
fmt.Println("5.ReplaceAllLiteral 字节字面量:", string(resByte2))
// 6.ReplaceAllFunc 字节回调自定义逻辑
bytePrice := []byte("标价5 标价15")
resByte3 := numRe.ReplaceAllFunc(bytePrice, func(b []byte) []byte {
val, _ := strconv.Atoi(string(b))
return []byte(strconv.Itoa(val + 10))
})
fmt.Println("6.ReplaceAllFunc 字节数值加10", string(resByte3))
}