为了方便提取,我们会把正则表达式中要提取的数据使用命名方式来书写正则表达式。这个技术在Go语言中如何实现,可以看下面这篇博客:
Using the Go Regexp Package
http://blog.kamilkisiel.net/blog/2012/07/05/using-the-go-regexp-package/
简单期间,这里复制其中几个例子的代码:
我们期望在字符串 1000abcd123 中找出前后两个数字。
例子1:匹配到这个字符串的例子
- packagemain
- import(
- "fmt"
- "regexp"
- )
- vardigitsRegexp=regexp.MustCompile(`(\d+)\D+(\d+)`)
- funcmain(){
- someString:="1000abcd123"
- fmt.Println(digitsRegexp.FindStringSubmatch(someString))
- }
上面代码输出:
[1000abcd123 1000 123]
例子2:使用带命名的正则表达式
- packagemain
- import(
- "fmt"
- "regexp"
- )
- varmyExp=regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)
- funcmain(){
- fmt.Printf("%+v",myExp.FindStringSubmatch("1234.5678.9"))
- }
上面代码输出,所有匹配到的都输出了:
[1234.5678.9 1234 5678 9]
这里的Named capturing groups (?P<name>) 方式命名正则表达式是 python、Go语言特有的, java、c# 是 (?<name>) 命名方式。
参考: http://www.crifan.com/detailed_explanation_about_python_regular_express_match_named_group/
http://osdir.com/ml/go-language-discuss/2012-07/msg00605.html
Go 支持的正则表达式语法可以参看:https://code.google.com/p/re2/wiki/Syntax
例子3:对正则表达式类扩展一个获得所有命名信息的方法,并使用它。
- packagemain
- import(
- "fmt"
- "regexp"
- )
- //embedregexp.Regexpinanewtypesowecanextendit
- typemyRegexpstruct{
- *regexp.Regexp
- }
- //addanewmethodtoournewregularexpressiontype
- func(r*myRegexp)FindStringSubmatchMap(sstring)map[string]string{
- captures:=make(map[string]string)
- match:=r.FindStringSubmatch(s)
- ifmatch==nil{
- returncaptures
- }
- fori,name:=ranger.SubexpNames(){
- //Ignorethewholeregexpmatchandunnamedgroups
- ifi==0||name==""{
- continue
- }
- captures[name]=match[i]
- }
- returncaptures
- }
- //anexampleregularexpression
- varmyExp=myRegexp{regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)}
- funcmain(){
- mmap:=myExp.FindStringSubmatchMap("1234.5678.9")
- ww:=mmap["first"]
- fmt.Println(mmap)
- fmt.Println(ww)
- }
上面代码的输出结果:
map[first:1234 second:9]
1234
例子4,抓取限号信息,并记录到一个Map中。
- packagemain
- import(
- "fmt"
- iconv"github.com/djimenez/iconv-go"
- "io/IoUtil"
- "net/http"
- "os"
- "regexp"
- )
- //embedregexp.Regexpinanewtypesowecanextendit
- typemyRegexpstruct{
- *regexp.Regexp
- }
- //addanewmethodtoournewregularexpressiontype
- func(r*myRegexp)FindStringSubmatchMap(sstring)[](map[string]string){
- captures:=make([](map[string]string),0)
- matches:=r.FindAllStringSubmatch(s,-1)
- ifmatches==nil{
- returncaptures
- }
- names:=r.SubexpNames()
- for_,match:=rangematches{
- cmap:=make(map[string]string)
- forpos,val:=rangematch{
- name:=names[pos]
- ifname==""{
- continue
- }
- /*
- fmt.Println("+++++++++")
- fmt.Println(name)
- fmt.Println(val)
- */
- cmap[name]=val
- }
- captures=append(captures,cmap)
- }
- returncaptures
- }
// 抓取限号信息的正则表达式
var myExp=myRegexp{regexp.MustCompile(`自(?P<byear>[\d]{4})年(?P<bmonth>[\d]{1,2})月(?P<bday>[\d]{1,2})日至(?P<eyear>[\d]{4})年(?P<emonth>[\d]{1,2})月(?P<eday>[\d]{1,2})日,星期一至星期五限行机动车车牌尾号分别为:(?P<n11>[\d])和(?P<n12>[\d])、(?P<n21>[\d])和(?P<n22>[\d])、(?P<n31>[\d])和(?P<n32>[\d])、(?P<n41>[\d])和(?P<n42>[\d])、(?P<n51>[\d])和(?P<n52>[\d])`)}
- funcErrorAndExit(errerror){
- fmt.Fprintln(os.Stderr,err)
- os.Exit(1)
- }
- funcmain(){
- response,err:=http.Get("http://www.bjjtgl.gov.cn/zhuanti/10weihao/index.html")
- deferresponse.Body.Close()
- iferr!=nil{
- ErrorAndExit(err)
- }
- input,err:=IoUtil.ReadAll(response.Body)
- iferr!=nil{
- ErrorAndExit(err)
- }
- body:=make([]byte,len(input))
- iconv.Convert(input,body,"gb2312","utf-8")
- mmap:=myExp.FindStringSubmatchMap(string(body))
- fmt.Println(mmap)
- }
上述代码输出:[map[n32:0 n22:9 emonth:7 n11:3 n41:1 n21:4 n52:7 bmonth:4 n51:2 bday:9 n42:6 byear:2012 eday:7 eyear:2012 n12:8 n31:5]map[emonth:10 n41:5 n52:6 n31:4 byear:2012 n51:1 eyear:2012 n32:9 bmonth:7 n22:8 bday:8 n11:2 eday:6 n42:0 n21:3 n12:7]map[bday:7 n51:5 n22:7 n31:3 eday:5 n32:8 byear:2012 bmonth:10 emonth:1 eyear:2013 n11:1 n12:6 n52:0 n21:2 n42:9 n41:4]map[eyear:2013 byear:2013 n22:6 eday:10 bmonth:1 n41:3 n32:7 n31:2 n21:1 n11:5 bday:6 n12:0 n51:4 n42:8 emonth:4 n52:9]]这段代码首先下载北京市交管局的网页;然后把这个gb2312的页面转换成utf-8编码,然后用正则表达式提取其中的限号信息。 参考资料:marcinwyszynski / named_captures.go https://gist.github.com/marcinwyszynski/3889572/revisionsStefanSchroeder / Golang-Regex-Tutorialhttps://github.com/StefanSchroeder/Golang-Regex-TutorialUsing the Go Regexp Packagehttp://blog.kamilkisiel.net/blog/2012/07/05/using-the-go-regexp-package/ Go语言用正则表达式提取多个指定字符http://blog.sina.com.cn/s/blog_4b51d46901019c3x.html 用golang的正则regexp:去除HTML,CSS,SCRIPT代码,仅保留页面文字http://bpbp.iteye.com/blog/1668869re2https://code.google.com/p/re2/wiki/SyntaxGo by Example: Regular Expressionshttps://gobyexample.com/regular-expressionsGolang-Regex-Tutorial / 01-chapter0.markdown https://github.com/StefanSchroeder/Golang-Regex-Tutorial/blob/master/01-chapter0.markdown