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

Given the line that represents the credit card number ...

val creditCardNo = "1111222233334444" 

... how to mask the first 12 characters with * ?

 val maskedCreditCardNo = "************4444" 
+5
source share
3 answers

Replace all numeric characters if 4 characters are left:

 creditCardNo.replaceAll("\\d(?=\\d{4})", "*") 
+6
source

Just use drop or substring on the source number and add the correct number "*":

 "*" * 12 + (creditCardNo drop 12) 
+14
source

An approach in which you can change the symbol values ​​for each position, in this case those before position 12 ,

 creditCardNo.zipWithIndex.map (c => if (c._2 < 12) '*' else c._1 ).mkString 

Please note that despite the ability to change each position separately, this is not the most efficient way to manipulate strings.

+1
source

Source: https://habr.com/ru/post/1216362/


All Articles