如何在Go中编写正则表达式以匹配最后一个单个空格?

huangapple go评论80阅读模式
英文:

How do I write regexp for the last occurence of single whitespace in Go?

问题

我想将字符串中的最后一个单个空格替换为其他内容。我该如何在Golang中编写正则表达式来匹配最后一个空格?到目前为止,我只知道\s+可以匹配所有空格。

英文:

I would like to replace the last single whitespace in a string with something else. How can I write regular expression for the last whitespace in Golang? So far I've only figured out that \s+ matches all whitespaces

答案1

得分: 3

你可以使用这个正则表达式:

\s(\S*)$

这个正则表达式匹配一个空白字符,后面跟着任意非空白字符(\S*),一直到字符串的末尾($)。

你可以用下面的方式替换最后一个空白字符:

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

$1 是捕获组 (\S*),用来保留空格后面的内容。你可以用任何你想要替换空白字符的字符来替换 "-" 字符。

英文:

You can use this regular expression:

\s(\S*)$

This matches a whitespace character that is followed by any non-white characters (\S*) up to the end of the string ($).

You can replace that last whitespace character like this:

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

The $1 is the captured group (\S*), to preserve the rest of the content after the space. Just replace the "-" character with whatever you want to replace the whitespace character with.

huangapple
  • 本文由 发表于 2023年2月11日 20:34:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75420251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定