Go正则表达式匹配字符串,替换字符串方式
更新时间:2025年02月25日 09:18:56 作者:Laravel技术社区
介绍了Go语言中使用正则表达式进行字符串匹配和替换的方法,包括匹配单个子字符串和所有子字符串,个人经验分享,旨在为读者提供实用的编程技巧,并鼓励大家支持脚本之家
Go正则表达式匹配字符串,替换字符串
正则表达式
package main
import (
"fmt"
"regexp"
)
func main() {
match, err := regexp.MatchString("h[a-z]+.*d$", "hello world")
if err != nil {
panic(err)
}
fmt.Println(match)
match, err = regexp.MatchString("h[a-z]+.*d$", "ello world")
if err != nil {
panic(err)
}
fmt.Println(match)
}
// $ go run main.go
// 输出如下
/**
true
false
*/匹配所有子字符串
package main
import (
"fmt"
"regexp"
)
func main() {
c, err := regexp.Compile("h[a-z]")
if err != nil {
panic(err)
}
res := c.FindAllString("hello world", -1)
fmt.Printf("res = %v\n", res)
res2 := c.FindAllString("hello world hi ha h1", -1)
fmt.Printf("res2 = %v\n", res2)
}
// $ go run main.go
// 输出如下
/**
res = [he]
res2 = [he hi ha]
*/替换所有子字符串
package main
import (
"fmt"
"regexp"
)
func main() {
c, err := regexp.Compile("h[a-z]")
if err != nil {
panic(err)
}
res := c.ReplaceAll([]byte("hello world"), []byte("?"))
fmt.Printf("res = %s\n", res)
res2 := c.ReplaceAll([]byte("hello world hi ha h1"), []byte("?"))
fmt.Printf("res2 = %s\n", res2)
}
// $ go run main.go
// 输出如下
/**
res = ?llo world
res2 = ?llo world ? ? h1
*/匹配中文
package main
import (
"fmt"
"regexp"
)
func main() {
match, err := regexp.MatchString("\\x{4e00}-\\x{9fa5}", "hello world")
if err != nil {
panic(err)
}
fmt.Println(match)
match, err = regexp.MatchString("\\p{Han}+", "hello 世界")
if err != nil {
panic(err)
}
fmt.Println(match)
}
// $ go run main.go
// 输出如下
/**
false
true
*/
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Golang 使用os 库的 ReadFile() 读文件最佳实践
这篇文章主要介绍了Golang使用os库的ReadFile()读文件最佳实践,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下2022-09-09
CSP communicating sequential processes并发模型
这篇文章主要为大家介绍了CSP communicating sequential processes并发模型,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-05-05


最新评论