技术栈系列基础篇4-正则表达式

正则工具

正则视图工具

https://regex-vis.com/

一、正则基础概念

1.1 正则思维导图

image.png
image.png

1.2 正则表达式元字符

字符

描述

'\\'

将下一个字符标记为一个特殊字符、或一个原义字符、或一个 向后引用、或一个八进制转义符。例如,'n' 匹配字符 "n"。'\\n' 匹配一个换行符。序列 '\\' 匹配 "\\" 而 "(" 则匹配 "("。

^

匹配输入字符串的开始位置。如果设置了 RegExp 对象的 Multiline 属性,^ 也匹配 '\\n' 或 '\\r' 之后的位置。

$

匹配输入字符串的结束位置。如果设置了RegExp 对象的 Multiline 属性,$ 也匹配 '\\n' 或 '\\r' 之前的位置。

*

匹配前面的子表达式零次或多次。例如,zo 能匹配 "z" 以及 "zoo"。 等价于{0,}。

+

匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。

?

匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 。? 等价于 {0,1}。

{n}

n 是一个非负整数。匹配确定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。

{n,}

n 是一个非负整数。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。

{n,m}

m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。

?

当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如,对于字符串 "oooo",'o+?' 将匹配单个 "o",而 'o+' 将匹配所有 'o'。

.

匹配除换行符(\\n、\\r)之外的任何单个字符。要匹配包括 \\n 在内的任何字符,请使用像"(.|\\n)"的模式。

(pattern)

匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中则使用 $0…$9 属性。要匹配圆括号字符,请使用 '(' 或 ')'。

(?:pattern)

匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用 "或" 字符 (|) 来组合一个模式的各个部分是很有用。例如, 'industr(?:y|ies) 就是一个比 'industry|industries' 更简略的表达式。

(?=pattern)

正向肯定预查(look ahead positive assert),在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如,"Windows(?=95|98|NT|2000)"能匹配"Windows2000"中的"Windows",但不能匹配"Windows3.1"中的"Windows"。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。

(?!pattern)

正向否定预查(negative assert),在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如"Windows(?!95|98|NT|2000)"能匹配"Windows3.1"中的"Windows",但不能匹配"Windows2000"中的"Windows"。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。

(?<=pattern)

反向(look behind)肯定预查,与正向肯定预查类似,只是方向相反。例如,"(?<=95|98|NT|2000)Windows"能匹配"2000Windows"中的"Windows",但不能匹配"3.1Windows"中的"Windows"。

(?<!pattern)

反向否定预查,与正向否定预查类似,只是方向相反。例如"(?<!95|98|NT|2000)Windows"能匹配"3.1Windows"中的"Windows",但不能匹配"2000Windows"中的"Windows"。

x\\|y

匹配 x 或 y。例如,'z|food' 能匹配 "z" 或 "food"。'(z|f)ood' 则匹配 "zood" 或 "food"。

[xyz]

字符集合。匹配所包含的任意一个字符。例如, 'abc' 可以匹配 "plain" 中的 'a'。

[^xyz]

负值字符集合。匹配未包含的任意字符。例如, '^abc' 可以匹配 "plain" 中的'p'、'l'、'i'、'n'。

[a-z]

字符范围。匹配指定范围内的任意字符。例如,'a-z' 可以匹配 'a' 到 'z' 范围内的任意小写字母字符。

[^a-z]

负值字符范围。匹配任何不在指定范围内的任意字符。例如,'^a-z' 可以匹配任何不在 'a' 到 'z' 范围内的任意字符。

\\b

匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。

\\B

匹配非单词边界。'er\\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。

\\cx

匹配由 x 指明的控制字符。例如, \\cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。

\\d

匹配一个数字字符。等价于 0-9。

\\D

匹配一个非数字字符。等价于 ^0-9。

\\f

匹配一个换页符。等价于 \\x0c 和 \\cL。

\\n

匹配一个换行符。等价于 \\x0a 和 \\cJ。

\\r

匹配一个回车符。等价于 \\x0d 和 \\cM。

\\s

匹配任何空白字符,包括空格、制表符、换页符等等。等价于 \\f\\n\\r\\t\\v。

\\S

匹配任何非空白字符。等价于 ^ \\f\\n\\r\\t\\v。

\\t

匹配一个制表符。等价于 \\x09 和 \\cI。

\\v

匹配一个垂直制表符。等价于 \\x0b 和 \\cK。

\\w

匹配字母、数字、下划线。等价于'A-Za-z0-9_'。

\\W

匹配非字母、数字、下划线。等价于 '^A-Za-z0-9_'。

\\xn

匹配 n,其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如,'\\x41' 匹配 "A"。'\\x041' 则等价于 '\\x04' & "1"。正则表达式中可以使用 ASCII 编码。

\\num

匹配 num,其中 num 是一个正整数。对所获取的匹配的引用。例如,'(.)\\1' 匹配两个连续的相同字符。

\\n

标识一个八进制转义值或一个向后引用。如果 \\n 之前至少 n 个获取的子表达式,则 n 为向后引用。否则,如果 n 为八进制数字 (0-7),则 n 为一个八进制转义值。

\\nm

标识一个八进制转义值或一个向后引用。如果 \\nm 之前至少有 nm 个获得子表达式,则 nm 为向后引用。如果 \\nm 之前至少有 n 个获取,则 n 为一个后跟文字 m 的向后引用。如果前面的条件都不满足,若 n 和 m 均为八进制数字 (0-7),则 \\nm 将匹配八进制转义值 nm。

\\nml

如果 n 为八进制数字 (0-3),且 m 和 l 均为八进制数字 (0-7),则匹配八进制转义值 nml。

\\un

匹配 n,其中 n 是一个用四个十六进制数字表示的 Unicode 字符。例如, \\u00A9 匹配版权符号 (?)。

1.3 修饰符

g 修饰符

g 修饰符可以查找字符串中所有的匹配项:

在字符串中查找 "runoob":

var str="Google runoob taobao runoob"; 
var n1=str.match(/runoob/);   // 查找第一次匹配项
var n2=str.match(/runoob/g);  // 查找所有匹配项

i 修饰符

i 修饰符为不区分大小写匹配,实例如下:

在字符串中查找 "runoob":

var str="Google runoob taobao RUNoob"; 
var n1=str.match(/runoob/g);   // 区分大小写
var n2=str.match(/runoob/gi);  // 不区分大小写

m 修饰符

m 修饰符可以使 ^ 和 $ 匹配一段文本中每行的开始和结束位置。

g 只匹配第一行,添加 m 之后实现多行。

以下实例字符串中使用 \\n 来换行:

在字符串中查找 "runoob":

var str="runoobgoogle\\ntaobao\\nrunoobweibo";
var n1=str.match(/^runoob/g);   // 匹配一个
var n2=str.match(/^runoob/gm);  // 多行匹配

s 修饰符

默认情况下的圆点 . 是 匹配除换行符 \\n 之外的任何字符,加上 s 之后, . 中包含换行符 \\n。

var str="google\\nrunoob\\ntaobao";
var n1=str.match(/google./);   // 没有使用 s,无法匹配\\n
var n2=str.match(/runoob./s);  // 使用 s,匹配\\n

1.4 括号的作用

1.4.1 小括号

作用:进行分组和捕获,其中,$1、$2表达的是正则表达式中小括号(即分组)中的内容,$1是第一个小括号(分组)中的匹配结果,$2是第二个小括号(分组)中的匹配结果

小括号内为子表达式

1.4.2 中括号

1.4.3 大括号

1.5 其他

正则 Regex 中$1,$2的含义

$1、$2表达的是正则表达式中小括号(即分组)中的内容,$1是第一个小括号(分组)中的匹配结果,$2是第二个小括号(分组)中的匹配结果,以此类推。通常$1、$2用在替换操作中。如下:

image.png

比如 hell(\\w+?)world(\\d+)

匹配 helloworld123

$1= 括号里的 o

$2= 第2个括号里的 123

正则 (。|$)小括号表达式中$字符的意思

$ 标识字符串结尾的意思,在这段表达式的意思是,例如 我是邬先生。我是邬先生 可以匹配的上

image.png

二、golang regexp包详解

2.1 附regexp测试用例

golang regexp包,附上测试用例最全面

regexp/example_test.go

// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package regexp_test

import (
	"fmt"
	"regexp"
	"strings"
)

func Example() {
	// Compile the expression once, usually at init time.
	// Use raw strings to avoid having to quote the backslashes.
	var validID = regexp.MustCompile(`^[a-z]+\\[[0-9]+\\]$`)

	fmt.Println(validID.MatchString("adam[23]"))
	fmt.Println(validID.MatchString("eve[7]"))
	fmt.Println(validID.MatchString("Job[48]"))
	fmt.Println(validID.MatchString("snakey"))
	// Output:
	// true
	// true
	// false
	// false
}

func ExampleMatch() {
	matched, err := regexp.Match(`foo.*`, []byte(`seafood`))
	fmt.Println(matched, err)
	matched, err = regexp.Match(`bar.*`, []byte(`seafood`))
	fmt.Println(matched, err)
	matched, err = regexp.Match(`a(b`, []byte(`seafood`))
	fmt.Println(matched, err)

	// Output:
	// true <nil>
	// false <nil>
	// false error parsing regexp: missing closing ): `a(b`
}

func ExampleMatchString() {
	matched, err := regexp.MatchString(`foo.*`, "seafood")
	fmt.Println(matched, err)
	matched, err = regexp.MatchString(`bar.*`, "seafood")
	fmt.Println(matched, err)
	matched, err = regexp.MatchString(`a(b`, "seafood")
	fmt.Println(matched, err)
	// Output:
	// true <nil>
	// false <nil>
	// false error parsing regexp: missing closing ): `a(b`
}

func ExampleQuoteMeta() {
	fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))
	// Output:
	// Escaping symbols like: \\.\\+\\*\\?\\(\\)\\|\\[\\]\\{\\}\\^\\$
}

func ExampleRegexp_Find() {
	re := regexp.MustCompile(`foo.?`)
	fmt.Printf("%q\\n", re.Find([]byte(`seafood fool`)))

	// Output:
	// "food"
}

func ExampleRegexp_FindAll() {
	re := regexp.MustCompile(`foo.?`)
	fmt.Printf("%q\\n", re.FindAll([]byte(`seafood fool`), -1))

	// Output:
	// ["food" "fool"]
}

func ExampleRegexp_FindAllSubmatch() {
	re := regexp.MustCompile(`foo(.?)`)
	fmt.Printf("%q\\n", re.FindAllSubmatch([]byte(`seafood fool`), -1))

	// Output:
	// [["food" "d"] ["fool" "l"]]
}

func ExampleRegexp_FindSubmatch() {
	re := regexp.MustCompile(`foo(.?)`)
	fmt.Printf("%q\\n", re.FindSubmatch([]byte(`seafood fool`)))

	// Output:
	// ["food" "d"]
}

func ExampleRegexp_Match() {
	re := regexp.MustCompile(`foo.?`)
	fmt.Println(re.Match([]byte(`seafood fool`)))
	fmt.Println(re.Match([]byte(`something else`)))

	// Output:
	// true
	// false
}

func ExampleRegexp_FindString() {
	re := regexp.MustCompile(`foo.?`)
	fmt.Printf("%q\\n", re.FindString("seafood fool"))
	fmt.Printf("%q\\n", re.FindString("meat"))
	// Output:
	// "food"
	// ""
}

func ExampleRegexp_FindStringIndex() {
	re := regexp.MustCompile(`ab?`)
	fmt.Println(re.FindStringIndex("tablett"))
	fmt.Println(re.FindStringIndex("foo") == nil)
	// Output:
	// [1 3]
	// true
}

func ExampleRegexp_FindStringSubmatch() {
	re := regexp.MustCompile(`a(x*)b(y|z)c`)
	fmt.Printf("%q\\n", re.FindStringSubmatch("-axxxbyc-"))
	fmt.Printf("%q\\n", re.FindStringSubmatch("-abzc-"))
	// Output:
	// ["axxxbyc" "xxx" "y"]
	// ["abzc" "" "z"]
}

func ExampleRegexp_FindAllString() {
	re := regexp.MustCompile(`a.`)
	fmt.Println(re.FindAllString("paranormal", -1))
	fmt.Println(re.FindAllString("paranormal", 2))
	fmt.Println(re.FindAllString("graal", -1))
	fmt.Println(re.FindAllString("none", -1))
	// Output:
	// [ar an al]
	// [ar an]
	// [aa]
	// []
}

func ExampleRegexp_FindAllStringSubmatch() {
	re := regexp.MustCompile(`a(x*)b`)
	fmt.Printf("%q\\n", re.FindAllStringSubmatch("-ab-", -1))
	fmt.Printf("%q\\n", re.FindAllStringSubmatch("-axxb-", -1))
	fmt.Printf("%q\\n", re.FindAllStringSubmatch("-ab-axb-", -1))
	fmt.Printf("%q\\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
	// Output:
	// [["ab" ""]]
	// [["axxb" "xx"]]
	// [["ab" ""] ["axb" "x"]]
	// [["axxb" "xx"] ["ab" ""]]
}

func ExampleRegexp_FindAllStringSubmatchIndex() {
	re := regexp.MustCompile(`a(x*)b`)
	// Indices:
	//    01234567   012345678
	//    -ab-axb-   -axxb-ab-
	fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
	fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
	fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
	fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
	fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
	// Output:
	// [[1 3 2 2]]
	// [[1 5 2 4]]
	// [[1 3 2 2] [4 7 5 6]]
	// [[1 5 2 4] [6 8 7 7]]
	// []
}

func ExampleRegexp_FindSubmatchIndex() {
	re := regexp.MustCompile(`a(x*)b`)
	// Indices:
	//    01234567   012345678
	//    -ab-axb-   -axxb-ab-
	fmt.Println(re.FindSubmatchIndex([]byte("-ab-")))
	fmt.Println(re.FindSubmatchIndex([]byte("-axxb-")))
	fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-")))
	fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-")))
	fmt.Println(re.FindSubmatchIndex([]byte("-foo-")))
	// Output:
	// [1 3 2 2]
	// [1 5 2 4]
	// [1 3 2 2]
	// [1 5 2 4]
	// []
}

func ExampleRegexp_Longest() {
	re := regexp.MustCompile(`a(|b)`)
	fmt.Println(re.FindString("ab"))
	re.Longest()
	fmt.Println(re.FindString("ab"))
	// Output:
	// a
	// ab
}

func ExampleRegexp_MatchString() {
	re := regexp.MustCompile(`(gopher){2}`)
	fmt.Println(re.MatchString("gopher"))
	fmt.Println(re.MatchString("gophergopher"))
	fmt.Println(re.MatchString("gophergophergopher"))
	// Output:
	// false
	// true
	// true
}

func ExampleRegexp_NumSubexp() {
	re0 := regexp.MustCompile(`a.`)
	fmt.Printf("%d\\n", re0.NumSubexp())

	re := regexp.MustCompile(`(.*)((a)b)(.*)a`)
	fmt.Println(re.NumSubexp())
	// Output:
	// 0
	// 4
}

func ExampleRegexp_ReplaceAll() {
	re := regexp.MustCompile(`a(x*)b`)
	fmt.Printf("%s\\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))
	fmt.Printf("%s\\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
	fmt.Printf("%s\\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
	fmt.Printf("%s\\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
	// Output:
	// -T-T-
	// --xx-
	// ---
	// -W-xxW-
}

func ExampleRegexp_ReplaceAllLiteralString() {
	re := regexp.MustCompile(`a(x*)b`)
	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
	// Output:
	// -T-T-
	// -$1-$1-
	// -${1}-${1}-
}

func ExampleRegexp_ReplaceAllString() {
	re := regexp.MustCompile(`a(x*)b`)
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
	// Output:
	// -T-T-
	// --xx-
	// ---
	// -W-xxW-
}

func ExampleRegexp_ReplaceAllStringFunc() {
	re := regexp.MustCompile(`[^aeiou]`)
	fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))
	// Output:
	// SeaFooD FooL
}

func ExampleRegexp_SubexpNames() {
	re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
	fmt.Println(re.MatchString("Alan Turing"))
	fmt.Printf("%q\\n", re.SubexpNames())
	reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
	fmt.Println(reversed)
	fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
	// Output:
	// true
	// ["" "first" "last"]
	// ${last} ${first}
	// Turing Alan
}

func ExampleRegexp_SubexpIndex() {
	re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
	fmt.Println(re.MatchString("Alan Turing"))
	matches := re.FindStringSubmatch("Alan Turing")
	lastIndex := re.SubexpIndex("last")
	fmt.Printf("last => %d\\n", lastIndex)
	fmt.Println(matches[lastIndex])
	// Output:
	// true
	// last => 2
	// Turing
}

func ExampleRegexp_Split() {
	a := regexp.MustCompile(`a`)
	fmt.Println(a.Split("banana", -1))
	fmt.Println(a.Split("banana", 0))
	fmt.Println(a.Split("banana", 1))
	fmt.Println(a.Split("banana", 2))
	zp := regexp.MustCompile(`z+`)
	fmt.Println(zp.Split("pizza", -1))
	fmt.Println(zp.Split("pizza", 0))
	fmt.Println(zp.Split("pizza", 1))
	fmt.Println(zp.Split("pizza", 2))
	// Output:
	// [b n n ]
	// []
	// [banana]
	// [b nana]
	// [pi a]
	// []
	// [pizza]
	// [pi a]
}

func ExampleRegexp_Expand() {
	content := []byte(`
	# comment line
	option1: value1
	option2: value2

	# another comment line
	option3: value3
`)

	// Regex pattern captures "key: value" pair from the content.
	pattern := regexp.MustCompile(`(?m)(?P<key>\\w+):\\s+(?P<value>\\w+)$`)

	// Template to convert "key: value" to "key=value" by
	// referencing the values captured by the regex pattern.
	template := []byte("$key=$value\\n")

	result := []byte{}

	// For each match of the regex in the content.
	for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
		// Apply the captured submatches to the template and append the output
		// to the result.
		result = pattern.Expand(result, template, content, submatches)
	}
	fmt.Println(string(result))
	// Output:
	// option1=value1
	// option2=value2
	// option3=value3
}

func ExampleRegexp_ExpandString() {
	content := `
	# comment line
	option1: value1
	option2: value2

	# another comment line
	option3: value3
`

	// Regex pattern captures "key: value" pair from the content.
	pattern := regexp.MustCompile(`(?m)(?P<key>\\w+):\\s+(?P<value>\\w+)$`)

	// Template to convert "key: value" to "key=value" by
	// referencing the values captured by the regex pattern.
	template := "$key=$value\\n"

	result := []byte{}

	// For each match of the regex in the content.
	for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
		// Apply the captured submatches to the template and append the output
		// to the result.
		result = pattern.ExpandString(result, template, content, submatches)
	}
	fmt.Println(string(result))
	// Output:
	// option1=value1
	// option2=value2
	// option3=value3
}

func ExampleRegexp_FindIndex() {
	content := []byte(`
	# comment line
	option1: value1
	option2: value2
`)
	// Regex pattern captures "key: value" pair from the content.
	pattern := regexp.MustCompile(`(?m)(?P<key>\\w+):\\s+(?P<value>\\w+)$`)

	loc := pattern.FindIndex(content)
	fmt.Println(loc)
	fmt.Println(string(content[loc[0]:loc[1]]))
	// Output:
	// [18 33]
	// option1: value1
}

func ExampleRegexp_FindAllSubmatchIndex() {
	content := []byte(`
	# comment line
	option1: value1
	option2: value2
`)
	// Regex pattern captures "key: value" pair from the content.
	pattern := regexp.MustCompile(`(?m)(?P<key>\\w+):\\s+(?P<value>\\w+)$`)
	allIndexes := pattern.FindAllSubmatchIndex(content, -1)
	for _, loc := range allIndexes {
		fmt.Println(loc)
		fmt.Println(string(content[loc[0]:loc[1]]))
		fmt.Println(string(content[loc[2]:loc[3]]))
		fmt.Println(string(content[loc[4]:loc[5]]))
	}
	// Output:
	// [18 33 18 25 27 33]
	// option1: value1
	// option1
	// value1
	// [35 50 35 42 44 50]
	// option2: value2
	// option2
	// value2
}

func ExampleRegexp_FindAllIndex() {
	content := []byte("London")
	re := regexp.MustCompile(`o.`)
	fmt.Println(re.FindAllIndex(content, 1))
	fmt.Println(re.FindAllIndex(content, -1))
	// Output:
	// [[1 3]]
	// [[1 3] [4 6]]
}

2.2 regexp的几个使用示例

<font color=red>示例:我最爱的city是哪个location</font>

package main

import (
	"fmt"
	"regexp"
)

func main() {
	src := "我最爱的[city]是哪个[location]"
	rule1 := `\\[[\\s\\S]*?\\]` // /s:任意空白符,/S:任意非空白符,*:匹配0个或更多个元素,?:陪陪0个或1个;*?: 懒惰模式,匹配最短的数据
	r1 := regexp.MustCompile(rule1)
	// 提取出[city]、[location]
	list := r1.FindAllString(src, -1) // 找到所有匹配的数据
	fmt.Println("list:", list)        // output: ["[city]","[]"]
	// 提取出”我最爱的是哪个“,即去掉标签信息
	unLabelSrc := r1.ReplaceAllString(src, "") // 将匹配到的子串用,空字符串替代
	fmt.Println("unLabelSrc:", unLabelSrc)
	// 在[city]、[location]中提取出,city、location
	if len(list) == 0 {
		return
	}
	// 使用`\\[(.*?)\\]` 或 `\\[(\\s|\\S*?)\\]` 均可
	rule2 := `\\[(.*?)\\]` // .:匹配除了\\n之外的任何字符,*?:懒惰模式,最短数据
	r2 := regexp.MustCompile(rule2)
	for _, v := range list {
		label := r2.ReplaceAllString(v, "$1")
		fmt.Println(label) // 分别输出,city,location
	}
}

提取年月日时分秒

package main

import (
	"fmt"
	"regexp"
)

func main() {
	r3 := regexp.MustCompile(`[:年月日号时点分秒\\-\\/\\n\\t ]`)
	dateStr := `2006年01月02日 15时04分05秒`
	v3 := r3.Split(dateStr, -1) // 以匹配到的元素进行分割字符串
	fmt.Println(v3)             // 输出 ”[2006 01 02  15 04 05 ]“ 处理数组时记得去掉空字符串
}

ReplaceAllString 示例详解

对“$1W” 的结果有些不理解,先说结论

$name or ${name}, where name is a non-empty sequence of letters, digits, and underscores. A reference to an out of range or unmatched index or a name that is not present in the regular expression is replaced with an empty slice.

In the $name form, name is taken to be as long as possible: $1x is equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.

So, in the 3rd replacement, $1W is treated as ${1W} and since this group is not initialized, an empty string is used for replacement.

所以这里的**fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))**, $1W 对应的就是 ${1W} 变量,但是这个变量不存在即空字符串,所以就相当于将 空字符串替换匹配的字符串。

func ExampleRegexp_ReplaceAllString() {
	re := regexp.MustCompile(`a(x*)b`)
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
	fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
	// Output:
	// -T-T-
	// --xx-
	// ---
	// -W-xxW-
}

ReplaceAllString示例2,小括号的作用

func main() {
	rex := regexp.MustCompile(`a(\\d+)c(\\d+)`)
	s := `ba12c34d`
	fmt.Println(rex.Match([]byte(s)))
	//
	s1 := rex.ReplaceAllString(s, "$1")
	fmt.Println(s1)
	s2 := rex.ReplaceAllString(s, "$2")
	fmt.Println(s2)
}

output: true  b12d b34d

ReplaceAllString替换匹配到的数据,$1是子表达式第一个小括号的数据,$2是第二个括号的数据

匹配表达式是 a(\\d+)c(\\d+) ,其中第一个小括号里面的子表达式是 \\d+ $1为12,第二个小括号里面的子表达式是\\d+ $2为34, ReplaceAllString 作用就是,首先匹配到ba12c34d,匹配的内容是 a12c34

  • 将第一个小括号里面的子表达式匹配的 12,替换 a12c34,结果为b12d
  • 将第二个小括号里面的子表达式匹配的 34,替换 a12c34,结果为b34d

汉字、字母、数字、下划线正则

^[\\u3400-\\u4dbf\\u4e00-\\u9fffA-Za-z0-9_]+$

本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
技术栈系列基础篇4-正则表达式
默认情况下的圆点 . 是 匹配除换行符 \\n 之外的任何字符,加上 s 之后, . 中包含换行符 \\n。
<<上一篇
下一篇>>