- Go Systems Programming
- Mihalis Tsoukalos
- 268字
- 2021-07-02 18:08:02
Find and replace
The example in this subsection will search the provided text for two variations of a given string and replace it with another string. The program will be named findReplace.go and will actually use Go regular expressions. The main reason for using the regexp.Compile() function, in this case, is that it greatly simplifies things and allows you to access your text only once.
The first part of the findReplace.go program is as follows:
package main import ( "fmt" "os" "regexp" )
The next part is as follows:
func main() { var s [3]string s[0] = "1 b 3" s[1] = "11 a B 14 1 1" s[2] = "b 2 -3 B -5" parse, err := regexp.Compile("[bB]")
if err != nil { fmt.Printf("Error compiling RE: %s\n", err) os.Exit(-1) }
The previous Go code will find every occurrence of an uppercase B or a lowercase b ([bB]). Note that there is also regexp.MustCompile() that works like regexp.Compile(). However, regexp.MustCompile() does not return an error variable; it just panics if the given expression is erroneous and cannot be parsed. As a result, regexp.Compile() is a better choice.
The last part is as follows:
for i := 0; i < len(s); i++ { temp := parse.ReplaceAllString(s[i], "C") fmt.Println(temp) } }
Here you replace each match with an uppercase C using parse.ReplaceAllString().
Executing findReplace.go generates the expected output:
$ go run findReplace.go 1 C 3 11 a C 14 1 1 C 2 -3 C -5
- JavaScript 從入門(mén)到項(xiàng)目實(shí)踐(超值版)
- 深度學(xué)習(xí)經(jīng)典案例解析:基于MATLAB
- 自己動(dòng)手實(shí)現(xiàn)Lua:虛擬機(jī)、編譯器和標(biāo)準(zhǔn)庫(kù)
- Mastering SVG
- C#程序設(shè)計(jì)(慕課版)
- MySQL 8 DBA基礎(chǔ)教程
- Visual Basic程序設(shè)計(jì)(第3版):學(xué)習(xí)指導(dǎo)與練習(xí)
- Java游戲服務(wù)器架構(gòu)實(shí)戰(zhàn)
- Hands-On JavaScript High Performance
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- AutoCAD VBA參數(shù)化繪圖程序開(kāi)發(fā)與實(shí)戰(zhàn)編碼
- 軟件架構(gòu):Python語(yǔ)言實(shí)現(xiàn)
- Nexus規(guī)模化Scrum框架
- 第一行代碼 C語(yǔ)言(視頻講解版)
- Kotlin極簡(jiǎn)教程