简体   繁体   中英

Censor Characters between the first and last character of a string in elixir

I want to replace/censor the characters of a username in elixir. So in the end, it should looks like in the bidders list in ebay: 在此处输入图像描述

in elixir there is the String replace function, but i am a newbe at regex and i dont know what elixir-regex supports. so how can i achieve this?

iex> String.replace("username1234", someregex, "***")
"u***4"

While you surely might accomplish this with regex “replace all but the first and the last symbols”

String.replace "username1234", ~r/(?<=\A.).*(?=.\z)/, "***"
#⇒ "u***4"

I'd better go with String.slice/3

first = String.slice("username1234", 0, 1)
last = String.slice("username1234", -1, 1)
"#{first}***#{last}"
#⇒ "u***4"

or String.graphemes/1

[h | t] = String.graphemes("username1234")
h <> "***" <> List.last(t)
#⇒ "u***4"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM