Home > Backend Development > Golang > Replace '.' with '_' Golang

Replace '.' with '_' Golang

PHPz
Release: 2024-02-09 11:12:23
forward
1132 people have browsed it

代替 ”。”与“_”Golang

php editor Youzi today introduces you to a very practical Golang language feature - the replacement operator (_). In Golang, the substitution operator can be used to ignore the value of a variable or expression, making the code more concise and readable. By using substitution operators, we can avoid unnecessary variable assignments or function return value processing, improving code readability and execution efficiency. Next, we will introduce the usage and precautions of the substitution operator in detail to help everyone better understand and apply this practical feature.

Question content

I have been doing go programming on codewars as a hobby and stumbled upon the following tasks:

The code provided should replace all dots. In the specified string with a dash - But it doesn't work properly. Mission: Fix the bug so we can get home early.

Initial error code:

regexp.mustcompile(`.`).replaceallstring(str, "-")
Copy after login

By brute force, I got it to work like this:

regexp.mustcompile(`[.]`).replaceallstring(str, "-")
Copy after login

The correct answer is obviously this:

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

Can someone explain the logic behind my solution and the correct solution? Thank you in advance!

Solution

Your solution is also correct.

In regular expressions, dot defines a special metacharacter , but in character classes it is a regular dot.

However, one can complain about the misleading impression of metacharacter usage, so the escape points are clearer and easier to understand.

The above is the detailed content of Replace '.' with '_' Golang. For more information, please follow other related articles on the PHP Chinese website!

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