KennethC
KennethC

Reputation: 756

java - replace a specific length of a digit in a sentence

I want to convert to asterisk the first 12 digits of a 16 digit number in a sentence.

The last 4 digits should be visible.

Example input:

String test = "test/1234567890121123/121/test";
String test2 = "hey: 1234567890123456";

Expected output:

String test = "test/************1123/121/test";
String test2 = "hey: ************3456";

Note: the input is dynamic

Upvotes: 0

Views: 979

Answers (2)

user unknown
user unknown

Reputation: 36229

Java:

test.replaceAll ("([0-9]{12})([0-9]{4})", "************$2/")

If only expressions of the exact right length (16) shall match, not longer ones:

-> "0123456789012345".replaceAll ("\\b([0-9]{12})([0-9]{4})\\b", "************$2/");
|  Expression value is: "************2345/"
|    assigned to temporary variable $18 of type String

Fails, too long:

-> "01234567890123456".replaceAll ("\\b([0-9]{12})([0-9]{4})\\b", "************$2/");
|  Expression value is: "01234567890123456"
|    assigned to temporary variable $19 of type String

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

Try this option:

String test = "test/1234567890121123/121/test";
String test2 = "hey: 1234567890123456";
test = test.replaceAll("\\b\\d{12}(?=\\d{4}\\b)", "************"); // 12 *'s
System.out.println(test);

The trick here is to surgically replace 12 digits at the beginning of a 16 digit number. To do this, we can search for \b\d{12}(?=\d{4}\b). The final portion of that pattern is a positive lookahead, which asserts, but does not consume. Since the lookahead does not actually consume, what it matches will not be affected by the replacement.

Demo

Upvotes: 6

Related Questions