我想知道如何删除:
- 全部leading/trailing个空格或换行符、空字符等.
- 字符串中的任何冗余空格(例如"hello[space][space]world"将转换为"hello[space]world")
对于单个正则表达式、对国际空格字符的Unicode支持等,这是可能的吗?
我想知道如何删除:
对于单个正则表达式、对国际空格字符的Unicode支持等,这是可能的吗?
似乎您可能希望同时使用\s
速记字符类和\p{Zs}
Unicode属性来匹配Unicode空格.但是,这两个步骤都不能用1个正则表达式替换来完成,因为您需要两个不同的替换,并且ReplaceAllStringFunc
只允许将整个匹配字符串作为参数(我不知道如何判断哪个组匹配).
因此,我建议使用两个regexp:
^[\s\p{Zs}]+|[\s\p{Zs}]+$
-匹配所有前导/尾随空格[\s\p{Zs}]{2,}
-匹配字符串内的2个或更多空格符号示例代码:
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)
}