问题描述

我想知道如何删除:

  • 所有前导/后缀空格或换行符,空字符等.
  • 字符串中的任何多余空格(例如,"hello [space] [space] world"将转换为"hello [space] world")

使用单个正则表达式,对国际空格字符的unicode支持等是否可行?

 \ s  \ p {Zs}  ReplaceAllStringFunc 

因此,我建议使用两个正则表达式:

 ^ [\ s \ p {Zs}] + | [\ s \ p {Zs}] + $  [\ s \ p {Zs}] {2,} 

示例代码:

 程序包主要进口 ("fmt"正则表达式")func main(){输入:=文本更多在这里"re_leadclose_whtsp:= regexp.MustCompile(`^ [\ s \ p {Zs}] + | [\ s \ p {Zs}] + $`)re_inside_whtsp:= regexp.MustCompile(`[\ s \ p {Zs}] {2,}`)最终:= re_leadclose_whtsp.ReplaceAllString(input,")最终= re_inside_whtsp.ReplaceAllString(final,")fmt.Println(最终)} 

I was wondering how to remove:

  • All leading/trailing whitespace or new-line characters, null characters, etc.
  • Any redundant spaces within a string (ex. "hello[space][space]world" would be converted to "hello[space]world")

Is this possible with a single Regex, with unicode support for international space characters, etc.?

\s\p{Zs}ReplaceAllStringFunc

Thus, I suggest using two regexps:

^[\s\p{Zs}]+|[\s\p{Zs}]+$[\s\p{Zs}]{2,}

Sample code:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    input := "   Text   More here     "
    re_leadclose_whtsp := regexp.MustCompile(`^[\s\p{Zs}]+|[\s\p{Zs}]+$`)
    re_inside_whtsp := regexp.MustCompile(`[\s\p{Zs}]{2,}`)
    final := re_leadclose_whtsp.ReplaceAllString(input, "")
    final = re_inside_whtsp.ReplaceAllString(final, " ")
    fmt.Println(final)
}

这篇关于如何从Golang中的字符串中删除多余的空格/空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!