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
相關用法
- GO Regexp.ExpandString用法及代碼示例
- GO Regexp.FindString用法及代碼示例
- GO Regexp.FindAllIndex用法及代碼示例
- GO Regexp.ReplaceAllLiteralString用法及代碼示例
- GO Regexp.FindStringSubmatch用法及代碼示例
- GO Regexp.FindAllString用法及代碼示例
- GO Regexp.FindAllStringSubmatch用法及代碼示例
- GO Regexp.SubexpIndex用法及代碼示例
- GO Regexp.Match用法及代碼示例
- GO Regexp.Longest用法及代碼示例
- GO Regexp.FindStringIndex用法及代碼示例
- GO Regexp.ReplaceAll用法及代碼示例
- GO Regexp.Find用法及代碼示例
- GO Regexp.SubexpNames用法及代碼示例
- GO Regexp.FindAllSubmatchIndex用法及代碼示例
- GO Regexp.FindSubmatchIndex用法及代碼示例
- GO Regexp.FindAllStringSubmatchIndex用法及代碼示例
- GO Regexp.MatchString用法及代碼示例
- GO Regexp.ReplaceAllString用法及代碼示例
- GO Regexp.FindIndex用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Regexp.Expand。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。