results := re.FindAllString("I have an apple and an axe here.", -1)
fmt.Println("Found all:", results) // 输出: Found all: [apple axe]
复制代码
3.4. 替换
使用 ReplaceAllString 替换匹配的子串。
replaced := re.ReplaceAllString("I have an apple and an axe here.", "fruit")
fmt.Println("Replaced:", replaced) // 输出: Replaced: I have an fruit and an fruit here.
复制代码
3.5. 分割字符串
使用 Split 函数按照正则表达式分割字符串。
splitStrings := re.Split("I have an apple and an axe here.", -1)
fmt.Println("Split:", splitStrings) // 输出: Split: [I have an and an here.]
复制代码
完整示例
下面是一个完整的示例,演示了上述功能:
package mainimport (
"fmt"
"regexp"
)
func main() { // 编译正则表达式 re := regexp.MustCompile("a([a-z]+)e")
// 匹配字符串 matched := re.MatchString("apple") fmt.Println("Matched:", matched) // 输出: Matched: true // 找到匹配的字符串 result := re.FindString("I have an apple here.") fmt.Println("Found:", result) // 输出: Found: apple // 找到全部匹配的字符串 results := re.FindAllString("I have an apple and an axe here.", -1) fmt.Println("Found all:", results) // 输出: Found all: [apple axe] // 替换匹配的子串 replaced := re.ReplaceAllString("I have an apple and an axe here.", "fruit") fmt.Println("Replaced:", replaced) // 输出: Replaced: I have an fruit and an fruit here. // 按照正则表达式分割字符串 splitStrings := re.Split("I have an apple and an axe here.", -1) fmt.Println("Split:", splitStrings) // 输出: Split: [I have an and an here.]}