将 “。” 替换为 “_” Golang

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

Replace "." with "_" Golang

问题

我一直在Codewars上作为一项爱好进行Go编程,并偶然遇到了以下任务:

提供的代码应该将指定字符串中的所有点.替换为破折号-
但它没有正常工作。
任务:修复错误,这样我们就可以提前回家了。

初始错误代码:

regexp.MustCompile(`.`).ReplaceAllString(str, "-")

通过蛮力法,我使它像这样工作:

regexp.MustCompile(`[.]`).ReplaceAllString(str, "-")

正确答案显然是这样的:

regexp.MustCompile(`\.`).ReplaceAllString(str, "-")

有人能解释一下我解决方案和正确解决方案背后的逻辑吗?
提前谢谢!

英文:

been doing Go programming on Codewars as a hobby and stumbled upon following task:

The code provided is supposed to replace all the dots . in the specified String with dashes -
But it's not working properly.
Task: Fix the bug so we can all go home early.

Initial wrong code:

regexp.MustCompile(`.`).ReplaceAllString(str, "-")

Through brute force, i've made it work like this:

regexp.MustCompile(`[.]`).ReplaceAllString(str, "-")

The correct answer is apparently this:

regexp.MustCompile(`\.`).ReplaceAllString(str, "-")

Could someone please explain the logic behind my solution and the right one.
Thank you in advance!

答案1

得分: 3

你的解决方案也是正确的。

在正则表达式中,点号(.)定义了一个特殊元字符,但在字符类(character class)中,它只表示一个普通的点号。

然而,对于元字符的使用可能会给人一种误导性的印象,因此转义的点号更清晰易懂。

英文:

Your solution is correct too.

In regex, the dot define a special metacharacter but inside a character class it's a regular dot.

It is possible however to complain about the misleading impression of metacharacter use, so the escaped dot is more clear and easy to understand.

huangapple
  • 本文由 发表于 2023年1月8日 19:27:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75047371.html
匿名

发表评论

匿名网友

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

确定