Home > Article > Backend Development > How to write a regular expression for the last occurrence of a single space in 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!