官术网_书友最值得收藏!

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
The awk(1) and sed(1) command-line tools can do most of the previous tasks more easily, but sed(1) and awk(1) are not general-purpose programming languages.
主站蜘蛛池模板: 鄱阳县| 新乐市| 泰兴市| 集贤县| 嘉荫县| 巴彦淖尔市| 肇东市| 房产| 正宁县| 上虞市| 华亭县| 芦溪县| 兴业县| 翼城县| 东安县| 静海县| 卫辉市| 尉犁县| 莱阳市| 罗江县| 留坝县| 新巴尔虎右旗| 高邑县| 金乡县| 景德镇市| 上栗县| 钟山县| 瑞丽市| 通渭县| 白朗县| 乐至县| 庆城县| 湄潭县| 遂宁市| 天门市| 项城市| 洞口县| 荆州市| 永顺县| 景德镇市| 昌宁县|