使用正则表达式进行正向回顾

Kur*_*eek 3 regex go

我正在尝试在 Go 中编写一个函数,它将替换foobarfoobaz,但前提是bar前面是foo。在我看来,该regexp.ReplaceAll函数与积极的lookbehind(参见https://www.regular-expressions.info/lookaround.html)一起可以解决这个问题,所以我尝试了以下方法:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    re := regexp.MustCompile(`(?<=foo)bar`)

    new := re.ReplaceAll([]byte("foobar"), []byte("baz"))

    fmt.Println(string(new))
}
Run Code Online (Sandbox Code Playgroud)

目标是让这个程序 print foobaz,但我却感到恐慌,因为正则表达式无法编译:

panic: regexp: Compile(`(?<=foo)bar`): error parsing regexp: invalid or unsupported Perl syntax: `(?<`
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

笔记

我尝试过的一件事是将正则表达式替换为非捕获组:

re := regexp.MustCompile(`(?:foo)bar`)
Run Code Online (Sandbox Code Playgroud)

但是,我发现程序随后打印baz而不是按foobaz预期打印。

zzn*_*zzn 6

看起来你的问题只是静态字符串替换。可以简单地用字符串完成。替换

但如果你确实想要回顾:

Go 的regexp包不支持lookbehind,你可以在这里查看支持的功能: https: //github.com/google/re2/wiki/Syntax

如果您确实需要lookbehind,您应该尝试第三方模块,例如: https: //github.com/dlclark/regexp2