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