Reputation: 14027
I have a string String email="[email protected]"
so its length is 24.
I want result like rachit************il.com.That means 1/4 of initial same and last 1/4 same.
Just want to convert 1/2 from middle to * with the help of regEX.
Thanks
Upvotes: 0
Views: 68
Reputation: 20025
You could convert to char array, process and convert back to String:
String email = "[email protected]";
char[] a = email.toCharArray();
for (int i = 0, j = a.length >> 2; i < a.length >> 1; i++, j++)
a[j] = '*';
email = new String(a);
Result:
rachit************il.com
You can't identify the middle of a string using a single regular expression unless the lengths have a finite number of values.
Upvotes: 1
Reputation: 1723
You could do something like this:
"[email protected]".replaceAll("(?<=.{5}).(?=.{5})", "*");
this will replace all characters to *
apart from the first and last 5.
In response to your question, you could make this flexible like this:
String email = "[email protected]";
int i = email.length() / 4;
email = email.replaceAll("(?<=.{" + i + "}).(?=.{" + i + "})", "*");
Just a word of warning, if you were to start using this in production code, you probably want to create a way of caching these regexes, based on the value of i
. This way is for demonstration of the pattern only, and will compile a regex Pattern
each time it is used.
Upvotes: 2
Reputation: 7032
One way to do it is to create a string of '*'
s that is the correct length, then concatenate on the surrounding parts of the original string. That way you don't have to do any looping:
public static String starize(String str){
char[] middle = new char[str.length()/2];
Arrays.fill(middle, '*');
return str.substring(0, str.length()/4)
+ String.copyValueOf(middle)
+ str.substring(3 * str.length() / 4);
}
Upvotes: 1