Home > Backend Development > Golang > Found an error in Golang Regexp ReplaceAllString?

Found an error in Golang Regexp ReplaceAllString?

王林
Release: 2024-02-13 15:51:17
forward
882 people have browsed it

Golang Regexp ReplaceAllString 中发现错误?

在Golang开发过程中,使用正则表达式进行字符串替换是常见的操作。然而,有时候在使用ReplaceAllString函数时可能会遇到一些错误。php小编柚子在这里为大家解答这个问题,帮助大家理解并解决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)//prints 'arted' expected: carted
}
Copy after login

去游乐场:https://go.dev/play/p/-f0cd_81emx

尝试使用非字母字符有效(即“$1.$2”会产生“.arted”)

添加多个字母字符是可行的(即“$1cl$2”会导致“clarted”)

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

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

解决方法

在你的替代品中:

`$1c$2`
Copy after login

这被解释为字面名为 $1c 的捕获组,该捕获组在正则表达式中不存在。您需要 ${1}c

The above is the detailed content of Found an error in Golang Regexp ReplaceAllString?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template