GO的正则的事项;

一、

Regexp包提供了16个方法,用于匹配正则表达式搜索结果。方法名满足如下正则表达式:

Find(All)?(String)?(Submatch)?(Index)?

Regexp包提供了16个方法,用于匹配正则表达式搜索结果。方法名满足如下正则表达式:

Find(All)?(String)?(Submatch)?(Index)?

RE2语法: https://github.com/google/re2


Find(All)?(String)?(Submatch)?(Index)?

如果'All'出现了,该方法会返回输入中所有互不重叠的匹配结果。如果一个匹配结果的前后(没有间隔字符)存在长度为0的成功匹配,该空匹配会被忽略。包含All的方法会要求一个额外的整数参数n,如果n>=0,方法会返回最多前n个匹配结果。

如果'String'出现了,匹配对象为字符串,否则应该是[]byte类型,返回值和匹配对象的类型是对应的。

如果'Submatch'出现了,返回值是表示正则表达式中成功的组匹配(子匹配/次级匹配)的切片。组匹配是正则表达式内部的括号包围的次级表达式(也被称为“捕获分组”),从左到右按左括号的顺序编号。,索引0的组匹配为完整表达式的匹配结果,1为第一个分组的匹配结果,依次类推。

如果'Index'出现了,匹配/分组匹配会用输入流的字节索引对表示result[2n:2n+1]表示第n个分组匹配的的匹配结果。如果没有'Index',匹配结果表示为匹配到的文本。如果索引为负数,表示分组匹配没有匹配到输入流中的文本。


分组:
     (re)           编号的捕获分组
        (?P<name>re)   命名并编号的捕获分组
        (?:re)         不捕获的分组
        (?flags)       设置当前所在分组的标志,不捕获也不匹配
        (?flags:re)    设置re段的标志,不捕获的分组

标志的语法为xyz(设置)、-xyz(清楚)、xy-z(设置xy,清楚z),标志如下:
        I              大小写敏感(默认关闭)
        m              ^和$在匹配文本开始和结尾之外,还可以匹配行首和行尾(默认开启)
        s              让.可以匹配\n(默认关闭)
        U              非贪婪的:交换x*和x*?、x+和x+?……的含义(默认关闭)

 //解释正则表达式
    reg := regexp.MustCompile(`<div>(?s:(.*?))</div>`)
    if reg == nil {
        fmt.Println("MustCompile err")
        return
    }
    //提取关键信息
    result := reg.FindAllStringSubmatch(buf, -1)
    //过滤<></>
    for _, text := range result {
        fmt.Println("text[1] = ", text[1])
    }

二、正则代码示例

package main

import (
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
)

func func19() {
	words := [...]string{"seven", "even", "Maven", "Amen", "eleven"}
	for _, word := range words {
		found, err := regexp.MatchString(".even", word)
		if err != nil {
			log.Fatal(err)
		}
		if found {
			fmt.Printf("%s matches\n", word)
		} else {
			fmt.Printf("%s does not match\n", word)
		}
	}
}

// func19 \20的结果

// seven matches
// even does not match
// Maven does not match
// Amen does not match
// eleven matches

// func19()
func funclab20() {
	words := [...]string{"seven", "even", "Maven", "Amen", "eleven"}

	ret := regexp.MustCompile(".even")
	for _, word := range words {
		fount := ret.MatchString(word)

		if fount {
			fmt.Printf("%s matches\n", word)
		} else {
			fmt.Printf("%s does not match\n", word)
		}

	}

}

// ​FindAllString​​ 查找所有出现的已定义正则表达式。第二个参数是要查找的最大匹配项; -1 表示搜索所有可能的匹配项。

// ​FindAllString​​ 函数返回正则表达式的所有连续匹配的切片。
// re := regexp.MustCompile("(?i)fox(es)?")
// 使用 (?i) 语法,正则表达式不区分大小写。 (es)?表示“es”字符可能包含零次或一次。

func findanchar() {
	var content = `Foxes are omnivorous mammals belonging to several genera
	of the family Canidae. Foxes have a flattened skull, upright triangular ears,
	a pointed, slightly upturned snout, and a long bushy tail. Foxes live on every
	continent except Antarctica. By far the most common and widespread species of
	fox is the red fox.foxe,foxes`

	re := regexp.MustCompile("(?i)fox(es)?")
	found := re.FindAllString(content, -1)
	fmt.Printf("%q\n", found)
	if found == nil {
		fmt.Printf("no match found\n")
		os.Exit(1)
	}
	for _, word := range found {
		fmt.Printf("%s\n", word)
	}

	// 	["Foxes" "Foxes" "Foxes" "fox" "fox" "fox" "foxes"]
	// Foxes
	// Foxes
	// Foxes
	// fox
	// fox
	// fox
	// foxes

}

func allindet() {
	var content = `Foxes are omnivorous mammals belonging to several genera
of the family Canidae. Foxes have a flattened skull, upright triangular ears,
a pointed, slightly upturned snout, and a long bushy tail. Foxes live on every
continent except Antarctica. By far the most common and widespread species of
fox is the red fox.`
	re := regexp.MustCompile("(?i)fox(es)?")
	idx := re.FindAllStringIndex(content, -1)
	for _, j := range idx {
		match := content[j[0]:j[1]]
		fmt.Printf("%s at %d:%d\n", match, j[0], j[1])
	}

	// Foxes at 0:5
	// Foxes at 80:85
	// Foxes at 194:199
	// fox at 292:295
	// fox at 307:310

}

//

// re := regexp.MustCompile(",\s*")正则表达式包括一个逗号字符和任意数量的相邻空格。

func splitfun() {
	var data = `22, 1, 3, 4, 5, 17, 4, 3, 21, 4, 5, 1, 48, 9, 42`
	sum := 0
	re := regexp.MustCompile(`,\s*`)
	vals := re.Split(data, -1)
	for _, val := range vals {
		n, err := strconv.Atoi(val)
		sum += n
		if err != nil {
			log.Fatal(err)
		}
	}
	fmt.Println(sum)

}

// 圆括号 () 用于创建捕获组。这允许我们将量词应用于整个组或将交替限制为正则表达式的一部分。
// 为了找到捕获组(Go 使用术语子表达式),我们使用 ​​FindStringSubmatch​​ 函数。
// 我们使用组将域名分为两部分。

// re := regexp.MustCompile("(\w+)\.(\w+)")
// 我们用括号定义了两个组。

// parts := re.FindStringSubmatch(website)
// ​​FindStringSubmatch​​ 返回包含匹配项的字符串切片,包括来自捕获组的字符串。

func fenzunew() {

	websites := [...]string{"webcode.me", "zetcode.com", "freebsd.org", "netbsd.org"}
	re := regexp.MustCompile(`(\w+)\.(\w+)`)
	for _, website := range websites {
		parts := re.FindStringSubmatch(website)
		for i, _ := range parts {

			fmt.Println(parts[i])
		}

		fmt.Println("---------------------")
	}

	// webcode.me
	// webcode
	// me
	// ---------------------
	// zetcode.com
	// zetcode
	// com
	// ---------------------
	// freebsd.org
	// freebsd
	// org
	// ---------------------
	// netbsd.org
	// netbsd
	// org
	// ---------------------

}

// Go 正则表达式捕获组

// ReplaceAllString​​ 替换字符串。该方法返回修改后的字符串

// https://www.cnblogs.com/liabio/p/11696060.html

// 匹配体局网页中的jpg图片链接等信息
func pipeiflag() {
	//解释正则表达式
	tpurls := `<img class="main_img img-hover" data-imgurl="https://img0.baidu.com/it/u=2900833435,993445529&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=800&amp;h=500" src="https://img0.baidu.com/it/u=2900833435,993445529&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=800&amp;h=500" style="width: 268px; height: 168px;">


	<img class="main_img img-hover" data-imgurl="https://img0.baidu.com/it/u=242767209,2541342896&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" src="https://img0.baidu.com/it/u=242767209,2541342896&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" style="width: 296px; height: 167px;">`

	reg := regexp.MustCompile(`src="(?s:(.*?))" style="(?s:(.*?));">`)
	if reg == nil {
		fmt.Println("MustCompile err")
		return
	}
	//提取关键信息
	result := reg.FindAllStringSubmatch(tpurls, -1)
	//过滤<></>
	for _, text := range result {
		fmt.Println("text[1] = ", text[1])
		fmt.Println("text[2] = ", text[2])
		fmt.Println()
		fmt.Println("text = ", text)
		fmt.Println("++++++++++++++++++++++")
	}

}

func pipeistlab2() {

	str := `==jsonDetailText=="Viewed Product",{"currency":"USD","variantId":41635375382697,"productId":7302746734761,"productGid":"gid:\/\/shopify\/Product\/7302746734761","name":"Ultimate Sports Bra® - Prism Blue - XSmall","price":"75.00","sku":"110002-371","brand":"Shefit","variant":"XSmall","category":"Ultimate - Limited Edition","nonInteraction":true});====`
	re, _ := regexp.Compile(`\"Viewed Product\",(.+)\);`)
	result := re.FindAllStringSubmatch(str, -1)
	fmt.Println(len(result))
	fmt.Println(result)
	fmt.Println(len(result[0]))
	fmt.Println(result[0])
	fmt.Println(result[0][0])
	fmt.Println(result[0][1])
}
func main() {
	// regexp包实现了正则表达式搜索。采用RE2语法(除了c、C),和Perl、Python等语言的正则基本一致。
	// func19()

	// funclab20()
	// findanchar()
	// allindet()
	// splitfun()
	// fenzunew()
	// pipeiflag()
	pipeistlab2()

}

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐