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


GO Regexp.ExpandString用法及代码示例

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

用法:

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

ExpandString 类似于 Expand 但模板和源是字符串。它附加并返回一个字节片,以便让调用代码控制分配。

例子:

package main

import (
    "fmt"
    "regexp"
)

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

输出:

option1=value1
option2=value2
option3=value3

相关用法


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