在Golang的Regexp ReplaceAllString中发现了一个错误吗?

huangapple go评论90阅读模式
英文:

Bug found in Golang Regexp ReplaceAllString?

问题

package main

import (
	"fmt"
	"regexp"
)

const sample = `darted`

func main() {
	var re = regexp.MustCompile(`^(.*?)d(.*)$`)
	s := re.ReplaceAllString(sample, `$1c$2`)
	fmt.Println(s) // 输出 'arted',预期输出:'carted'
}

Go playground: https://go.dev/play/p/-f0Cd_81eMX

尝试使用非字母字符是有效的(例如 $1.$2 的结果是 .arted

添加多个字母字符也是有效的(例如 $1cl$2 的结果是 clarted

为什么上面的示例不起作用?

有人可以告诉我我做错了什么,或者确认这是Go中需要报告的错误吗?

英文:
package main

import (
	"fmt"
	"regexp"
)

const sample = `darted`

func main() {
	var re = regexp.MustCompile(`^(.*?)d(.*)$`)
	s := re.ReplaceAllString(sample, `$1c$2`)
	fmt.Println(s)//prints 'arted' expected: carted
}

Go playground: https://go.dev/play/p/-f0Cd_81eMX

Trying a non-alpha characters works (i.e. '$1.$2' results in '.arted')

Adding more than one alpha character works (i.e. '$1cl$2' results in 'clarted')

Why doesn't the above sample work?

Can someone show me what I'm doing wrong, or confirm this is a bug in Go that needs to be reported?

答案1

得分: 3

在你的替换部分:

`$1c$2`

这被解释为一个字面上命名为$1c的捕获组,而在正则表达式中并不存在。你想要的是${1}c

英文:

In your replacement:

`$1c$2`

This is as interpreted as a capture group literally named $1c which doesn't exist in the regex. You want ${1}c.

huangapple
  • 本文由 发表于 2023年5月26日 09:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定