go库函数之-regexp-使用示例

//############################################################
//D:\go\go\go库源码\源码库测试文件集合\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.
   // 编译解析一个正则表达式,并且如果成功返回一个可以用来匹配文本的 Regexp 对象,但如果表达式不能被解析就会panic
   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() {
   // 匹配检查文本正则表达式是否与字节片匹配。更复杂的查询需要使用 Compile 和完整的 Regexp 接口
   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() {
   // 检查文本正则表达式是否匹配字符串。更复杂的查询需要使用 Compile 和完整的 Regexp 接口
   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() {
   // 返回一个字符串,它引用参数文本中的所有正则表达式元字符; 返回的字符串是一个匹配文本文本的正则表达式。例如,QuoteMeta([foo])返回\[foo\]
   // 特殊字符有:\.+*?()|[]{}^$
   // 这些字符用于实现正则语法,所以当作普通字符使用时需要转换
   fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))
   // Output:
   // Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
}

func ExampleRegexp_Find() {
   // 编译解析一个正则表达式,并且如果成功返回一个可以用来匹配文本的 Regexp 对象
   re := regexp.MustCompile(`foo.?`)
   // 查找字节切片,返回第一个匹配的内容,re.Find
   fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))

   // Output:
   // "food"
}

func ExampleRegexp_FindAll() {
   re := regexp.MustCompile(`foo.?`)
   // 查找字节切片,返回所有匹配的内容
   // 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项
   //fmt.Printf("%q\n", r.FindAll([]byte(data), -1))
   fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))

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

func ExampleRegexp_FindAllSubmatch() {
   re := regexp.MustCompile(`foo(.?)`)
   // 查找字节切片,返回所有匹配的内容
   // 同时返回子表达式匹配的内容
   // [ [[完整匹配项], [子匹配项], [子匹配项], ...], [[完整匹配项], [子匹配项], [子匹配项], ...] ]
   //fmt.Printf("%q\n", r.FindAllSubmatch([]byte(data), -1))
   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`)))

   // Output:
   // true
}

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.`)
   // 查找字符串,返回所有匹配的内容
   // 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项
   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-
   // 查找字节切片,返回所有匹配的位置
   // 同时返回子表达式匹配的位置
   // 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项
   // [ [完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...], [完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...]... ]
   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_MatchString() {
   re := regexp.MustCompile(`(gopher){2}`)
   // 检查文本正则表达式是否匹配字符串。更复杂的查询需要使用 Compile 和完整的 Regexp 接口
   fmt.Println(re.MatchString("gopher"))
   fmt.Println(re.MatchString("gophergopher"))
   fmt.Println(re.MatchString("gophergophergopher"))
   // Output:
   // false
   // true
   // true
}

func ExampleRegexp_ReplaceAllLiteralString() {
   re := regexp.MustCompile(`a(x*)b`)
   // 在 src 中搜索匹配项,并替换为 repl 指定的内容
   // 如果 repl 中有“分组引用符”($1、$name),则将“分组引用符”当普通字符处理
   // 全部替换,并返回替换后的结果
   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`)
   // 在 src 中搜索匹配项,并替换为 repl 指定的内容
   // 全部替换,并返回替换后的结果
   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]`)
   // 在 src 中搜索匹配项,然后将匹配的内容经过 repl方法 处理后,替换 src 中的匹配项
   // 如果 repl 的返回值中有“分组引用符”($1、$name),则将“分组引用符”当普通字符处理
   // 全部替换,并返回替换后的结果
   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"))
   // 返回分组名称列表,未命名的分组返回空字符串
   // 返回值[0] 为整个正则表达式的名称
   // 返回值[1] 是分组 1 的名称
   // 返回值[2] 是分组 2 的名称
   //fmt.Println(r.SubexpNames())
   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_Split() {
   a := regexp.MustCompile(`a`)
   // 将a以指定字符分割成string数组
   //strings.Split(a, b)
   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.
      // 使用指定函数替换s中的${var}或$var。例如,os.ExpandEnv(s)等价于os.Expand(s, os.Getenv)
      //fmt.Println(os.Expand("Hello $NAME!", func(s string) string { return "Gopher" }))
      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) {
   // 将 template 的内容经过处理后,追加到 dst 的尾部
   // template 中要有 $1、$2、${name1}、${name2} 这样的“分组引用符”
   // match 是由 FindSubmatchIndex 方法返回的结果,里面存放了各个分组的位置信息
   // 如果 template 中有“分组引用符”,则以 match 为标准,
   // 在 src 中取出相应的子串,替换掉 template 中的 $1、$2 等引用符号。
      // 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+)$`)

   // 查找字节切片,返回第一个匹配的位置
   // [起始位置, 结束位置]
   //fmt.Println(r.FindIndex([]byte(data)))
   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+)$`)
   // 查找字节切片,返回所有匹配的位置
   // 同时返回子表达式匹配的位置
   // 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项
   // [ [完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...], [完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...]... ]
   //fmt.Println(r.FindAllSubmatchIndex([]byte(data), -1))
   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
}

猜你喜欢

转载自blog.csdn.net/liao__ran/article/details/114668106
今日推荐