You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:42:33