码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言的正则表式之regexp包

时间:2018-10-06 22:35:47      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:[1]   ext2   重叠   mpi   Go语言   reg   UNC   exp   project   

正则表达式都是大同小异,随便写几个案例:
// code_029_regexp project main.go
package main

import (
    "fmt"
    "regexp"
)

//Go中的正则表达式
func main() {
    //返回保管正则表达式所有不重叠的匹配结果的[]string切片。如果没有匹配到,会返回nil。
    //案例1
    context1 := "3.14 123123 .68 haha 1.0 abc 6.66 123."
    exp1 := regexp.MustCompile(`\d+\.\d+`)
    result1 := exp1.FindAllStringSubmatch(context1, -1)
    fmt.Printf("%v\n", result1)
    //案例2
    context2 := `
        <title>标题</title>
        <div>你过来啊</div>
        <div>hello mike</div>
        <div>你大爷</div>
        <body>呵呵</body>
    `
    exp2 := regexp.MustCompile(`<div>(.*?)</div>`)
    result2 := exp2.FindAllStringSubmatch(context2, -1)
    fmt.Printf("%v\n", result2)
    //案例3:
    context3 := `
        <title>标题</title>
        <div>你过来啊</div>
        <div>hello 
        mike
        go</div>
        <div>你大爷</div>
        <body>呵呵</body>
    `
    exp3 := regexp.MustCompile(`<div>(?s:(.*?))</div>`) //这里包含空格和换行
    result3 := exp3.FindAllStringSubmatch(context3, -1)
    fmt.Printf("%v\n", result3)
    //案例4:
    context4 := `
        <title>标题</title>
        <div>你过来啊</div>
        <div>hello 
        mike
        go</div>
        <div>你大爷</div>
        <body>呵呵</body> 
    `
    for _, text := range result4 {
        fmt.Println(text[0])
        fmt.Println(text[1])
        fmt.Println("===========\n")
    }
}

Go语言的正则表式之regexp包

标签:[1]   ext2   重叠   mpi   Go语言   reg   UNC   exp   project   

原文地址:http://blog.51cto.com/13914991/2294160

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!