Go正則表達式匹配字符串,替換字符串方式
更新時間:2025年02月25日 09:18:56 作者:Laravel技術社區(qū)
介紹了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并發(fā)模型
這篇文章主要為大家介紹了CSP communicating sequential processes并發(fā)模型,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05

