求助:Go语言正则如何匹配首个`.`之前的所有内容
在Go中匹配第一个
.之前的内容的解决方法 嘿,我知道你在Go里用正则匹配第一个.前内容遇到的问题了!你之前在其他语言用的/.+?(?=\.)/之所以在Go里失效,核心原因是Go标准库的regexp包采用RE2语法,不支持正向预查(也就是(?=\.)这种写法)。
下面给你两种靠谱的解决思路,按需选择:
方法一:改用支持RE2语法的正则(捕获组方式)
我们可以放弃预查,直接用匹配非.字符的方式,从字符串开头捕获到第一个.之前的内容,正则表达式写成^([^.]+):
package main import ( "fmt" "regexp" ) func main() { targetStr := `hostkafka1.kafka.server:type=BrokerTopicMetrics,name=FailedProduceRequestsPerSec,topic=auto.tooling.files.received.v1.MeanR^Cost","metric_path":"dsdpecard01kfk06.kafka.server:type=BrokerTopicMetrics,name=FailedProduceRequestsPerSec,topic=credit-card.servicing.accounts.authorized-user.created.v1.MeanRate","type":null,"region":"us-east-1` // 编译正则,捕获开头到第一个.的所有非.字符 re := regexp.MustCompile(`^([^.]+)`) matchResult := re.FindStringSubmatch(targetStr) if len(matchResult) > 1 { fmt.Println("匹配结果:", matchResult[1]) // 输出 hostkafka1 } else { fmt.Println("未找到匹配的内容") } }
这个正则的逻辑很清晰:^确保从字符串开头匹配,[^.]+匹配一个或多个非.的字符,用括号把这部分作为捕获组,最后通过FindStringSubmatch取出捕获组的内容即可。
方法二:不用正则,直接用字符串截取(更高效)
如果只是简单的截取第一个.前的内容,其实没必要用正则,Go的strings包提供的Index方法可以直接找到第一个.的位置,然后截取字符串,性能更好,代码也更直观:
package main import ( "fmt" "strings" ) func main() { targetStr := `hostkafka1.kafka.server:type=BrokerTopicMetrics,name=FailedProduceRequestsPerSec,topic=auto.tooling.files.received.v1.MeanR^Cost","metric_path":"dsdpecard01kfk06.kafka.server:type=BrokerTopicMetrics,name=FailedProduceRequestsPerSec,topic=credit-card.servicing.accounts.authorized-user.created.v1.MeanRate","type":null,"region":"us-east-1` if dotIndex := strings.Index(targetStr, "."); dotIndex != -1 { fmt.Println("截取结果:", targetStr[:dotIndex]) // 输出 hostkafka1 } else { fmt.Println("字符串中未找到.") } }
这种方式避免了正则表达式的编译和匹配开销,对于这类简单场景非常推荐。
内容的提问来源于stack exchange,提问作者lightweight
相关产品推荐
相关产品推荐

