본문 바로가기
개발의 정석/언어

[#golang] 스페이스(white space) 여러 개를 1개로 바꾸기

by 발자개발 2020. 3. 30.

 

 

 

텍스트를 다듬다 보면 스페이스, 띄워쓰기(white space) 여러개를 1개로 바꾸고 싶을 때가 있다.

이 경우, 정규식으로 간단하게 해결할 수 있다.

package main

import (
	"regexp"
)

// RemoveMultiSpaces : 스페이스 삭제
func RemoveMultiSpaces(str string) string {
	reLeadcloseWhtsp := regexp.MustCompile(`^[\s\p{Zs}]+|[\s\p{Zs}]+$`)
	reInsideWhtsp := regexp.MustCompile(`[\s\p{Zs}]{2,}`)
	result := reLeadcloseWhtsp.ReplaceAllString(str, "")
	result = reInsideWhtsp.ReplaceAllString(result, " ")
	return result
}


func main() {
	input := "  Hello     World   :)  !  "
    result := RemoveMultiSpaces(input)
}

 

 

 

 

댓글