Go标准库无正则前瞻断言时,如何实现非消耗式匹配?
Go中捕获重叠子串的替代方案
针对字符串wednesdayes需要捕获wednesday和yes两个重叠子串的需求,由于Go标准库regexp不支持前瞻断言,可采用以下两种实用方案:
方案一:分两次独立匹配(推荐)
直接针对两个目标子串分别创建正则表达式,依次扫描原字符串即可。这种方式逻辑简单直观,适合明确的多目标匹配场景:
package main import ( "fmt" "regexp" ) func main() { input := "wednesdayes" // 定义两个目标正则 reWed := regexp.MustCompile(`wednesday`) reYes := regexp.MustCompile(`yes`) // 执行匹配并获取结果 matchWed := reWed.FindString(input) matchYes := reYes.FindString(input) // 输出结果 fmt.Println("捕获结果:") if matchWed != "" { fmt.Printf("- %s\n", matchWed) } if matchYes != "" { fmt.Printf("- %s\n", matchYes) } }
运行后会输出:
捕获结果: - wednesday - yes
方案二:自定义扫描逻辑(适合复杂场景)
如果需要更灵活的控制,可以手动遍历字符串的所有子串,筛选出符合要求的结果:
package main import ( "fmt" "strings" ) func main() { input := "wednesdayes" targets := []string{"wednesday", "yes"} var results []string for _, t := range targets { if strings.Contains(input, t) { results = append(results, t) } } fmt.Println("捕获结果:") for _, r := range results { fmt.Printf("- %s\n", r) } }
这种方式无需依赖正则,直接通过字符串包含判断实现,对于固定目标子串的匹配来说效率更高。
内容的提问来源于stack exchange,提问作者CJW
相关产品推荐
相关产品推荐

