Home > Backend Development > Golang > How to write a regular expression for the last occurrence of a single space in Go?

How to write a regular expression for the last occurrence of a single space in Go?

王林
Release: 2024-02-08 20:51:13
forward
1249 people have browsed it

如何在 Go 中为最后一次出现的单个空格编写正则表达式?

问题内容

我想用其他内容替换字符串中的最后一个空格。如何在 Golang 中为最后一个空格编写正则表达式?到目前为止我只发现 \s+ 匹配所有空格


正确答案


您可以使用此正则表达式:

\s(\s*)$
Copy after login

这匹配一个空白字符,后跟任何非白色字符 (\s*),直到字符串末尾 ($)。

您可以像这样替换最后一个空白字符:

s := "this is a string"
re := regexp.MustCompile(`\s(\S*)$`)
s2 := re.ReplaceAllString(s, "-$1") // "this is a-string"
Copy after login

$1 是捕获的组 (\s*),保留空格后的其余内容。只需将“-”字符替换为您想要替换空白字符的任何字符即可。

The above is the detailed content of How to write a regular expression for the last occurrence of a single space in Go?. 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