Макс Шмакс
Макс Шмакс

Reputation: 11

How to mask part of string with * in regex

I want to mask email adress in Java from

[email protected] 

to

s********[email protected] 

- mask local name without only first and last letter and i want to number of * match amount of replaced symbols

I need some expression like

 /^(.)(.*)(.)@(.*)$/    

and replace in part 2 each symbols with *

How can i do this in Java?

Upvotes: 1

Views: 10428

Answers (2)

Bush
Bush

Reputation: 261

This can be done using regex pattern (?<=.{1}).(?=[^@]*?.@).

Bifurcation below:

.{1} matches any character (except for line terminators)

(?=[^@]?@) Match a single character not present in the list below [^@]? *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy) @ matches the character @ literally (case sensitive)

Upvotes: 0

anubhava
anubhava

Reputation: 785256

You can use this regex with String#replaceAll:

String email = "[email protected]";

String masked = email.replaceAll("(?<=.).(?=[^@]*?.@)", "*");
//=> s********[email protected]

Upvotes: 2

Related Questions