Created
February 8, 2018 03:17
-
-
Save tomtsang/8fbf50e86d96b801b5118ac656094824 to your computer and use it in GitHub Desktop.
regexp-Compile.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment