Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: How to mask the first N characters of a string

Tags:

scala

Given a string that represents a credit card number...

val creditCardNo = "1111222233334444"

... how do I mask the first 12 characters with *?

val maskedCreditCardNo = "************4444"
like image 537
j3d Avatar asked Mar 28 '15 19:03

j3d


2 Answers

Just use drop or substring on the original number, and prepend the right number of "*":

"*" * 12 + (creditCardNo drop 12)
like image 170
DNA Avatar answered Oct 05 '22 11:10

DNA


Replace all digit symbols unless 4 characters remain:

creditCardNo.replaceAll("\\d(?=\\d{4})", "*")
like image 45
Sergii Lagutin Avatar answered Oct 05 '22 13:10

Sergii Lagutin