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!
CodePudding user response:
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.