Home  >  Article  >  Backend Development  >  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?

王林
王林forward
2024-02-08 20:51:131159browse

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

问题内容

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


正确答案


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

\s(\s*)$

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

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

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

$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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete