當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。