package main
import "bytes"
import "fmt"
import "regexp"
func main() {
// 是否匹配
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match)
// 上面我们直接使用了字符串模式,但是其他的regexp的任务你需要编写一个` `
//` regexp `结构优化。
r, _ := regexp.Compile("p([a-z]+)ch")
// 此结构体有很多方法,如何上面一样的匹配
fmt.Println(r.MatchString("peach"))
// 查找
fmt.Println(r.FindString("peach punch"))
// 查找第一个匹配的位置
fmt.Println(r.FindStringIndex("peach punch"))
// 全局和括号里面的子集
// for both `p([a-z]+)ch` and `([a-z]+)`.
fmt.Println(r.FindStringSubmatch("peach punch"))
// 全局和括号里面的子集的序号
fmt.Println(r.FindStringSubmatchIndex("peach punch"))
// 发现所有匹配的
fmt.Println(r.FindAllString("peach punch pinch", -1))
// 也适用于子集
fmt.Println(r.FindAllStringSubmatchIndex(
"peach punch pinch", -1))
// 第2个参数限制匹配的数量
fmt.Println(r.FindAllString("peach punch pinch", 2))
// 字符数组也可以
fmt.Println(r.Match([]byte("peach")))
// 当用正则表达式创建常量时你可以使用mustcompile变化编译。
r = regexp.MustCompile("p([a-z]+)ch")
fmt.Println(r)
// 替换
fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
// 自定义替换方式
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Dive Into Python 3
Mark Pilgrim / Apress / 2009-11-6 / USD 44.99
Mark Pilgrim's Dive Into Python 3 is a hands-on guide to Python 3 (the latest version of the Python language) and its differences from Python 2. As in the original book, Dive Into Python, each chapter......一起来看看 《Dive Into Python 3》 这本书的介绍吧!