golang 正则
无    2014-03-02 21:48:14    1317    0    0
life

首先得到一个regexp, 使用Compile(), (MustCompile()如果字符串不符合正则会panic)

再调用其它函数, 常用的有

  • 检测是否匹配 Match() bool 
  • 检测是否存在, 并返回匹配的字符串 Find(), FindAll(), 每一种都有String类型的相应函数, FindString(), FindAllString()
  • 检测子匹配, FindStringSubMatch(), FindAllStringSubMatch()...
  • 查找并替换, ReplaceAllString()
  • 分隔成数组, Split(), (strings包有个strings.Split(""), 这里用正则更强大)
func main() {
	str := "abcdefgabc"
	reg, _ := regexp.Compile("abc.*?")
	
	fmt.Println(reg.MatchString(str)) // 是否匹配 // true
	fmt.Println(reg.FindString(str)) // 查找匹配的字符串 // abc
	fmt.Println(reg.FindAllString(str, -1)) // 查找匹配的字符串 // [abc abc]
	str3 := reg.ReplaceAllString(str, "--") // 查找所有的, 并替换成
	fmt.Println(str3) //--defg--
	
// 子查询 str2 := "http://leanote.com, https://leanote.com/you" reg2, _ := regexp.Compile("(http|https)://(leanote.*?)") fmt.Println(reg2.FindStringSubmatch(str2)) // 只匹配一次 // [http://leanote.com http leanote.com], [0]是全部的, [1]是第1个子, fmt.Println(reg2.FindAllStringSubmatch(str2, -1)) // 查找所有的 // [[http://leanote http leanote] [https://leanote https leanote]] }

上一篇: goeclipse不能保存项目配置

下一篇: revel 框架修改

1317 人读过