golang[68]-正则表达式支持

栏目: Go · 发布时间: 7年前

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))
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

社交天性

社交天性

[美] 马修·利伯曼(Matthew D. Lieberman) / 贾拥民 / 浙江人民出版社 / 2016-6 / 69.90

[内容简介] ● 《社交天性》是社会心理学家马修·利伯曼解读人类“社会脑”的权威之作,它告诉我们为什么在充满合作与竞争的智慧社会中人们喜爱社交又相互连接,个人的社会影响力如何得以发挥,书中处处充满了令人惊喜的洞见。 ● 为什么有的人天生善于社交,而有的人总是充满障碍? 为什么智商越高的人越难相处? 心痛对人的伤害甚至超过头痛? 慈善组织如何激发人们的捐赠行为? ......一起来看看 《社交天性》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具