Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all characters in string except last 4 characters

Using Go, how do I replace all characters in a string with "X" except the last 4 characters?

This works fine for php/javascript but not for golang as "?=" is not supported.

\w(?=\w{4,}$)

Tried this, but does not work. I couldn't find anything similar for golang

(\w)(?:\w{4,}$)

JavaScript working link

Go non-working link

like image 328
raghzz Avatar asked Jan 03 '23 19:01

raghzz


2 Answers

A simple yet efficient solution that handles multi UTF-8-byte characters is to convert the string to []rune, overwrite runes with 'X' (except the last 4), then convert back to string.

func maskLeft(s string) string {
    rs := []rune(s)
    for i := 0; i < len(rs)-4; i++ {
        rs[i] = 'X'
    }
    return string(rs)
}

Testing it:

fmt.Println(maskLeft("123"))
fmt.Println(maskLeft("123456"))
fmt.Println(maskLeft("1234世界"))
fmt.Println(maskLeft("世界3456"))

Output (try it on the Go Playground):

123
XX3456
XX34世界
XX3456

Also see related question: How to replace all characters in a string in golang

like image 178
icza Avatar answered Jan 05 '23 14:01

icza


Let's say inputString is the string you want to mask all the characters of (except the last four).

First get the last four characters of the string:

last4 := string(inputString[len(inputString)-4:])

Then get a string of X's which is the same length as inputString, minus 4:

re := regexp.MustCompile("\w")
maskedPart := re.ReplaceAllString(inputString[0:len(inputString)-5], "X")

Then combine maskedPart and last4 to get your result:

maskedString := strings.Join([]string{maskedPart,last4},"")
like image 32
Josh Withee Avatar answered Jan 05 '23 15:01

Josh Withee