Reputation: 604
Suggest I have follow two values:
123456789
123456789111
Does String.replaceAll can do follow?
123456789 -> XXXXXX789
123456789111 -> XXXXXXXXX111
for mask last three numberic, but replace other characters to X? Please noted the count of X in sample.
Thanks in advance.
Upvotes: 1
Views: 1057
Reputation: 174706
Yes, replaceAll function will do this job.
String s1 = "123456789";
String s2 = "123456789111";
System.out.println(s1.replaceAll("\\d(?=\\d{3})", "X"));
System.out.println(s2.replaceAll("\\d(?=\\d{3})", "X"));
Output:
XXXXXX789
XXXXXXXXX111
Explanation:
\\d(?=\\d{3})
Match a digit only if it's followed by three digits. So it fails for last three digits. Finally all the matched digits are replaced by the letter X
Upvotes: 3
Reputation: 36304
Yes you can:
public static void main(String[] args) {
String s1 = "123456789";
String s2 = "123456789111";
String regex = "\\d(?=\\d{3})"; // each digit followed by exactly 3 digits should be replaced by X
System.out.println(s1.replaceAll(regex, "X"));
System.out.println(s2.replaceAll(regex, "X"));
}
O/P :
XXXXXX789
XXXXXXXXX111
Upvotes: 0
Reputation: 67968
.(?!.{0,2}$)
Try this.Replace by X
.Put flags m
and g
.See demo.
http://regex101.com/r/sK8oK9/2
Upvotes: 1