- 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
- 垃圾回收的算法與實(shí)現(xiàn)
- Unity Virtual Reality Projects
- Mastering PHP Design Patterns
- Python 3破冰人工智能:從入門到實(shí)戰(zhàn)
- TypeScript項(xiàng)目開發(fā)實(shí)戰(zhàn)
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- INSTANT Yii 1.1 Application Development Starter
- Visual Studio 2015高級編程(第6版)
- Learning Node.js for .NET Developers
- 微課學(xué)人工智能Python編程
- PHP+MySQL動(dòng)態(tài)網(wǎng)站開發(fā)從入門到精通(視頻教學(xué)版)
- Mastering PowerCLI
- Access數(shù)據(jù)庫應(yīng)用教程(2010版)
- SQL Server on Linux
- Building a Media Center with Raspberry Pi