英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论