• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

[Go] 正则表达式 示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
package main

import "bytes"
import "fmt"
import "regexp"

func main() {
	// 1. 这个测试一个字符串是否符合一个表达式。
	match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
	fmt.Println("1.", match)

	// 上面我们是直接使用字符串,但是对于一些其他的正则任务,你需要使用 Compile 一个优化的 Regexp 结构体。
	r, _ := regexp.Compile("p([a-z]+)ch")

	// 2. 这个结构体有很多方法,这里是类似我们前面看到的一个匹配测试。
	fmt.Println("2.", r.MatchString("peach"))

	// 3. 这是查找匹配字符串的。
	fmt.Println("3.", r.FindString("peach punch"))

	// 4. 这个也是查找第一次匹配的字符串的,但是返回的匹配开始和结束位置索引,而不是匹配的内容。
	fmt.Println("4.", r.FindStringIndex("peach punch"))

	// 5. Submatch 返回 完全匹配 和 局部匹配 的字符串。例如,这里会返回 p([a-z]+)ch 和 ([a-z]+) 的信息。
	fmt.Println("5.", r.FindStringSubmatch("peach punch"))

	// 6. 类似的,这个会返回 完全匹配 和 局部匹配 的索引位置。
	fmt.Println("6.", r.FindStringSubmatchIndex("peach punch"))

	// 7. 带 All 的这个函数返回所有的匹配项,而不仅仅是首次匹配项。例如查找匹配表达式的所有项。
	fmt.Println("7.", r.FindAllString("peach punch pinch", -1))

	// 8. All 同样可以对应到上面的所有函数。
	fmt.Println("8.", r.FindAllStringSubmatchIndex("peach punch pinch", -1))

	// 9. 这个函数提供一个正整数来限制匹配次数。
	fmt.Println("9.", r.FindAllString("peach punch pinch", 2))

	// 10. 上面的例子中,我们使用了字符串作为参数,并使用了如 MatchString 这样的方法。我们也可以提供 []byte参数并将 String 从函数命中去掉。
	fmt.Println("10.", r.Match([]byte("peach")))

	// 11. 创建正则表示式常量时,可以使用 Compile 的变体MustCompile 。因为 Compile 返回两个值,不能用语常量。
	r = regexp.MustCompile("p([a-z]+)ch")
	fmt.Println("11.", r)

	// 12. regexp 包也可以用来替换部分字符串为其他值。
	fmt.Println("12.", r.ReplaceAllString("a peach", "<fruit>"))

	// 13. Func 变量允许传递匹配内容到一个给定的函数中,
	in := []byte("a peach")
	out := r.ReplaceAllFunc(in, bytes.ToUpper)
	fmt.Println("13.", string(out))
}

输出:

1. true
2. true
3. peach
4. [0 5]
5. [peach ea]
6. [0 5 1 3]
7. [peach punch pinch]
8. [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
9. [peach punch]
10. true
11. p([a-z]+)ch
12. a <fruit>
13. a PEACH

 

 

官方教程:http://studygolang.com/static/pkgdoc/pkg/regexp.htm


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go编写一个比特币交易自动出价程序发布时间:2022-07-10
下一篇:
分布式对象存储-可扩展的分布式系统--Go语言实现发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap