简体   繁体   中英

Replace "." with "_" Golang

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM