当前位置:网站首页>golang正则regexp包使用-04-使用正则替换(ReplaceAll(),ReplaceAllLiteral(),ReplaceAllFunc())
golang正则regexp包使用-04-使用正则替换(ReplaceAll(),ReplaceAllLiteral(),ReplaceAllFunc())
2022-06-23 04:46:00 【开发运维玄德公】
文章目录
| 方法 | 替换目标字串类型 | 替换源字串类型 | 返回值 | 返回类型 |
|---|---|---|---|---|
| ReplaceAll() | [ ]byte | [ ]byte | 返回被替换后的字串 | [ ]byte |
| ReplaceAllString() | string | string | 返回被替换后的字串 | string |
| ReplaceAllLiteral() | [ ]byte | [ ]byte | 返回被替换后的字串 | [ ]byte |
| ReplaceAllLiteralString() | string | string | 返回被替换后的字串 | string |
| ReplaceAllFunc() | [ ]byte | func() | 返回被替换后的字串 | [ ]byte |
| ReplaceAllStringFunc() | string | func() | 返回被替换后的字串 | string |
1. 正则替换
1.1 ReplaceAll() 方法
语法
func (re *Regexp) ReplaceAll(src []byte, repl []byte) []byte
完整示例
- 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("\\d+$")
myString := "10.10.239.11"
repl := "0/16"
s := reg.ReplaceAll([]byte(myString),[]byte(repl))
fmt.Printf("原字串:%q\n替换后:%q",myString,s)
}
- 结果
原字串:"10.10.239.11"
替换后:"10.10.239.0/16"
示例(使用分组 1)
- 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("(\\d.*\\.)\\d+")
myString := "10.10.239.11"
repl := "${1}0/16"
s := reg.ReplaceAll([]byte(myString),[]byte(repl))
fmt.Printf("原字串:%q\n替换后:%q",myString,s)
}
- 结果
原字串:"10.10.239.11"
替换后:"10.10.239.0/16"
示例(使用分组 2)
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("(.)(.)(.)(.)(.)(.)(.)")
myString := "柳庭风静人眠昼"
rep := []byte("${7}${6}${5}${4}${3}${2}${1}")
s := reg.ReplaceAll([]byte(myString),rep)
fmt.Printf("原字串:%q\n替换后:%q",myString,s)
}
- 结果
原字串:"柳庭风静人眠昼"
替换后:"昼眠人静风庭柳"
1.2 ReplaceAllString()
语法
func (re *Regexp) ReplaceAllString(src string, repl string) string
完整示例
- 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("\\d+$")
myString := "10.10.239.11"
repl := "0/16"
s := reg.ReplaceAllString(myString,repl)
fmt.Printf("原字串:%q\n替换后:%q",myString,s)
}
- 结果
原字串:"10.10.239.11"
替换后:"10.10.239.0/16"
2. 按原文替换
2.1 ReplaceAllLiteral()
“按原文的”说明rep中会按原文替换,即rep中的分组不会生效(我们将在“示例(按原文替换)”中演示。)
语法
func (re *Regexp) ReplaceAllLiteral(src []byte, repl []byte) []byte
完整示例
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("\\d+$")
myString := "10.10.239.11"
repl := "0/16"
s := reg.ReplaceAllLiteral([]byte(myString),[]byte(repl))
fmt.Printf("原字串:%q\n替换后:%q",myString,s)
}
- 显示结果
原字串:"10.10.239.11"
替换后:"10.10.239.0/16"
示例(按原文替换)
- 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("(\\d.*\\.)\\d+")
myString := "10.10.239.11"
repl := "${1}0/16"
s := reg.ReplaceAllLiteral([]byte(myString),[]byte(repl))
fmt.Printf("原字串:%q\n替换后:%q",myString,s)
}
- 结果
原字串:"10.10.239.11"
替换后:"${1}0/16"
如上可见,repl中的
${1}被原封不动的按字串替换了。
2.2 ReplaceAllLiteralString()
和ReplaceAllLiteral一样,repl中不可以使用分组的变量
语法
func (re *Regexp) ReplaceAllLiteralString(src string, repl string) string
完整示例
package main
import (
"fmt"
"regexp"
)
func main() {
//reg := regexp.MustCompile("(\\d.*\\.)\\d+")
reg := regexp.MustCompile("\\d+$")
myString := "10.10.239.11"
repl := "0/16"
s := reg.ReplaceAllLiteralString(myString,repl)
fmt.Printf("原字串:%q\n替换后:%q",myString,s)
}
- 结果
原字串:"10.10.239.11"
替换后:"10.10.239.0/16"
3. 函数处理替换源字串
3.1 ReplaceAllFunc()
语法
func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
ReplaceAllFunc()方法,初始化实例已经包含了正则,只需要传入:原字串(src)、要替换的字串(repl)。
repl是一个函数,传入值是正则匹配到的字串,传出一个经该函数处理过的值。
完整示例
- 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("\\w+$")
myString := "www.xishu.com"
result := reg.ReplaceAllFunc([]byte(myString),getRepl)
fmt.Printf("最终替换结果:%s\n",result )
}
func getRepl(match []byte) []byte {
var rspl []byte
fmt.Printf("正则匹配结果:%s\n",match)
rspl = append(rspl,match...)
rspl = append(rspl,".cn"...)
return rspl
}
- 结果
正则匹配结果:com
最终替换结果:www.xishu.com.cn
3.2 ReplaceAllStringFunc()
语法
func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string
完整示例
- 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("\\w+$")
myString := "www.xishu.com"
//repl := "0/16
result := reg.ReplaceAllStringFunc(myString,getRepl)
fmt.Printf("最终替换结果:%s\n",result )
}
func getRepl(match string) string {
var rspl string
fmt.Printf("正则匹配结果:%s\n",match)
rspl = match + ".cn"
return rspl
}
- 结果
正则匹配结果:com
最终替换结果:www.xishu.com.cn
边栏推荐
- matplotlib savefig多个图片叠加问题
- Remove duplicates from sorted list II of leetcode topic resolution
- 射频内容学习
- Day_13 傳智健康項目-第13章
- Eight data analysis models: ogsm model
- Ant Usage Summary (III): batch packaging apk
- Pyinstaller package exe setting icon is not displayed
- Tcp/ip explanation (version 2) notes / 3 link layer / 3.3 full duplex, energy saving, automatic negotiation mechanism, 802.1x flow control / 3.3.3 link layer flow control
- [cocos2d-x] screenshot sharing function
- (1) Basic learning - Common shortcut commands of vim editor
猜你喜欢

程序员的真实想法 | 每日趣闻

Radar canvas

Memory analysis and memory leak detection

【Leetcode】431. Encode n-ary tree to binary tree (difficult)

ant使用总结(二):相关命令说明

Detailed explanation of redis persistence, master-slave and sentry architecture

mongodb 4. X binding multiple IP startup errors

Day_ 01 smart communication health project - project overview and environmental construction

Day_09 传智健康项目-移动端开发-手机快速登录、权限控制

Progress of layer 2 technical scheme
随机推荐
Machine learning 3-ridge regression, Lasso, variable selection technique
【已解决】“The Unity environment took too long to respond. Make sure that :\n“
CPU的功能和基本结构
Basic RF theory (DB)
mongodb 4.x绑定多个ip启动报错
【Leetcode】431. Encode N-ary Tree to Binary Tree(困难)
Efficient office of fintech (I): automatic generation of trust plan specification
图解 Google V8 # 18 :异步编程(一):V8是如何实现微任务的?
论文笔记: 多标签学习 LSML
Day_ 09 smart health project - mobile terminal development - Mobile quick login and permission control
Microsoft interview question: creases in origami printing
Day_13 传智健康项目-第13章
Leetcode topic resolution integer to Roman
[database backup] complete the backup of MySQL database through scheduled tasks
求二叉树最宽的层有多少个节点
Learning Tai Chi Maker - esp8226 (11) distribution network with WiFi manager Library
[cocos2d-x] erasable layer:erasablelayer
去除防火墙和虚拟机对live555启动IP地址的影响
Vite learning (I) - Introduction
【Vivado那些事儿】XilinxCEDStore介绍