1 回答

TA貢獻1836條經驗 獲得超4個贊
這個正則表達式:
(?i)(This is a delimited string)|delimited|string
匹配這些文字字符串的最左邊最長的匹配項:
This is a delimited string
,delimited
, 或者string
將文本This is a delimited string, so let's go
提供給正則表達式,第一個選項匹配。它是唯一的匹配項,因為它同時消耗了delimited
和string
- 搜索在匹配項之后繼續進行。
將您的替代文本This is not a delimited string, so let's go
提供給正則表達式會產生 2 個匹配項,因為第一個替代文本不匹配,但第二個 ( delimited
) 和第三個 ( string
) 匹配。
如果您想知道匹配的備選方案,只需將每個備選方案括在括號中以使其成為捕獲組:
(?i)(This is a delimited string)|(delimited)|(string)`
現在我們可以檢查每個捕獲組的值:如果它的長度大于 1,則它是匹配的備選方案。
https://goplay.tools/snippet/nTm56_al__2
package main
import (
"fmt"
"regexp"
)
func main() {
str := "This is a delimited string, so let's go and find some delimited strings"
re := regexp.MustCompile(`(?i)(This is a delimited string)|(delimited)|(string)`)
matches := re.FindAllStringSubmatch(str, -1)
fmt.Println("Matches:", len(matches))
for i, match := range matches {
j := 1
for j < len(match) && match[j] == "" {
j++
}
fmt.Println("Match", i, "matched alternative", j, "with", match[j])
}
}
- 1 回答
- 0 關注
- 108 瀏覽
添加回答
舉報