mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 22:53:43 +08:00
第九章第二节,正则包的内容翻译
This commit is contained in:
56
eBook/09.2.md
Normal file
56
eBook/09.2.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
#9.2 regexp包
|
||||||
|
正则表达式语法和使用的详细信息请参考http://en.wikipedia.org/wiki/Regular_expression
|
||||||
|
|
||||||
|
在下面的程序里,我们将在字符串中对正则表达式进行匹配
|
||||||
|
|
||||||
|
如果是简单模式,使用Match方法便可: ok, _ := regexp.Match(pat, []byte(searchIn))
|
||||||
|
变量ok将返回true或者false,我们也可以使用MatchString: ok, _ := regexp.MathString(pat, searchIn)
|
||||||
|
|
||||||
|
更多方法中,必须先将正则通过Compile方法返回一个Regexp对象。然后我们将掌握一些匹配,查找,替换相关的功能。
|
||||||
|
|
||||||
|
示例 9.2 [pattern.go](exmaples/chapter_9/pattern.go)
|
||||||
|
|
||||||
|
package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
func main() {
|
||||||
|
//目标字符串
|
||||||
|
searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18"
|
||||||
|
pat := "[0-9]+.[0-9]+" //正则
|
||||||
|
|
||||||
|
f := func(s string) string{
|
||||||
|
v, _ := strconv.ParseFloat(s, 32)
|
||||||
|
return strconv.FormatFloat(v * 2, 'f', 2, 32)
|
||||||
|
}
|
||||||
|
|
||||||
|
if ok, _ := regexp.Match(pat, []byte(searchIn)); ok {
|
||||||
|
fmt.Println("Match Found!")
|
||||||
|
}
|
||||||
|
|
||||||
|
re, _ := regexp.Compile(pat)
|
||||||
|
//将匹配到的部分替换为"##.#"
|
||||||
|
str := re.ReplaceAllString(searchIn, "##.#")
|
||||||
|
fmt.Println(str)
|
||||||
|
//参数为函数时
|
||||||
|
str2 := re.ReplaceAllStringFunc(searchIn, f)
|
||||||
|
fmt.Println(str2)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
输出结果:
|
||||||
|
|
||||||
|
Match Found!
|
||||||
|
John: ##.# William: ##.# Steve: ##.#
|
||||||
|
John: 5156.68 William: 9134.46 Steve: 11264.36
|
||||||
|
|
||||||
|
Compile函数也可能返回一个错误,我们在使用时忽略对错误的判断是因为我们确信自己正则表达式是有效的。当用户输入或从数据中获取正则表达式的时候,我们有必要去检验它的正确性。另外我们也可以使用MustCompile方法,它可以像Compile方法一样检验正则的有效性,但是当正则不合法时程序将panic(详情查看13.2章节)。
|
||||||
|
|
||||||
|
|
||||||
|
##链接
|
||||||
|
- [目录](directory.md)
|
||||||
|
- 上一节:[标准库概述](09.1.md)
|
||||||
|
- 下一节:[锁和sync包](09.2.md)
|
Reference in New Issue
Block a user