加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

<16> go regexp正则

发布时间:2020-12-14 00:55:37 所属栏目:百科 来源:网络整理
导读:regexp包是go中内置的专门处理正则的包 package mainimport "bytes" import "fmt" import "regexp" func main() { // 正则,返回true 或者 false match,_ := regexp .MatchString ( "p([a-z]+)ch" , "peach" ) // true fmt .Println (match) // 返回regexp s

regexp包是go中内置的专门处理正则的包

package main
import "bytes"
import "fmt"
import "regexp"
func main() {
    // 正则,返回true 或者 false
    match,_ := regexp.MatchString("p([a-z]+)ch","peach")
    // true
    fmt.Println(match)
    // 返回regexp struct
    r,_ := regexp.Compile("p([a-z]+)ch")
    // 匹配单个字符串,true
    fmt.Println(r.MatchString("peach"))
    // 返回匹配的字符串 peach
    fmt.Println(r.FindString("peach punch"))
    // 返回匹配的字符串的下标数组 [0 5]
    fmt.Println(r.FindStringIndex("peach punch"))
    // 返回 p([a-z]+)ch 和 ([a-z]+)匹配的字符串,即匹配的字符串和匹配的内容,返回字符串数组 [peach ea]
    fmt.Println(r.FindStringSubmatch("peach punch"))
    // 匹配的字符串和匹配的内容的下标 [0 5 1 3]
    fmt.Println(r.FindStringSubmatchIndex("peach punch"))
    // 字符串里匹配的字符,返回字符串数组,无限制 [peach punch pinch]
    fmt.Println(r.FindAllString("peach punch pinch",-1))
    // [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
    fmt.Println(r.FindAllStringSubmatchIndex(
        "peach punch pinch",-1))
    // 字符串里匹配的字符,返回字符串数组,限制2个[peach punch]
    fmt.Println(r.FindAllString("peach punch pinch",2))
    // 字节匹配 true
    fmt.Println(r.Match([]byte("peach")))
    // 将匹配到的字符串进行处理
    r = regexp.MustCompile("p([a-z]+)ch")
    fmt.Println(r)// p([a-z]+)ch
    // a <fruit>
    fmt.Println(r.ReplaceAllString("a peach","<fruit>"))
    //  带函数的匹配处理 a PEACH
    in := []byte("a peach")
    out := r.ReplaceAllFunc(in,bytes.ToUpper)
    fmt.Println(string(out))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读