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


GO Regexp.SubexpIndex用法及代碼示例

GO語言"regexp"包中"Regexp.SubexpIndex"類型的用法及代碼示例。

用法:

func(re *Regexp) SubexpIndex(name string) int

SubexpIndex 返回具有給定名稱的第一個子表達式的索引,如果沒有具有該名稱的子表達式,則返回 -1。

請注意,可以使用相同的名稱編寫多個子表達式,例如 (?P<bob>a+)(?P<bob>b+),它聲明了兩個名為 "bob" 的子表達式。在這種情況下,SubexpIndex 返回正則表達式中最左邊的此類子表達式的索引。

例子:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
	fmt.Println(re.MatchString("Alan Turing"))
	matches := re.FindStringSubmatch("Alan Turing")
	lastIndex := re.SubexpIndex("last")
	fmt.Printf("last => %d\n", lastIndex)
	fmt.Println(matches[lastIndex])
}

輸出:

true
last => 2
Turing

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Regexp.SubexpIndex。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。