当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


GO Regexp.Expand用法及代码示例

GO语言"regexp"包中"Regexp.Expand"类型的用法及代码示例。

用法:

func(re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte

Expand 将模板附加到 dst 并返回结果;在追加期间,Expand 将模板中的变量替换为从 src 中提取的相应匹配项。匹配切片应该由FindSubmatchIndex返回

在模板中,变量由 $name 或 ${name} 形式的子字符串表示,其中 name 是字母、数字和下划线的非空序列。像 $1 这样的纯数字名称指的是具有相应索引的子匹配项;其他名称是指捕获以 (?P<name>...) 语法命名的括号。对超出范围或不匹配索引或正则表达式中不存在的名称的引用将替换为空切片。

在 $name 形式中,name 尽可能长:$1x 等价于 ${1x},而不是 ${1}x,并且,$10 等价于 ${10},而不是 ${1}0 .

要在输出中插入文字 $,请在模板中使用 $$。

例子:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    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))
}

输出:

option1=value1
option2=value2
option3=value3

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Regexp.Expand。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。