英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论