Sarika
Sarika

Reputation: 13

mask part of a string using regular expression

I would like to mask part of a string.For eg:

https://example.com/test?abc=12345678901234567890123456&mnr=12345678901234567890123456

to

https://example.com/test?abc=********************123456&mnr=12345678901234567890123456

I need to mask first 20 digits after "abc=" and keep last 6 digits as it is.

I tried (?<=abc=)(.*?)(?=&mnr) but it is showing example.com/test?abc=*&mnr=12345678901234567890123456

what will be the regular expression if abc= contains characters as well as numbers

Upvotes: 0

Views: 6509

Answers (2)

BullyBoo
BullyBoo

Reputation: 52

This regular will find the first 14 digit characters of abc paramter in the url:

(?<=abc=)[0-9]{14}(?=[0-9]{6})

Replacing:

String data = "https://example.com/test?abc=12345678901234567890123456&mnr=12345678901234567890123456";

String result = data.replaceAll("(?<=abc=)[0-9]{14}(?=[0-9]{6})",
            "**************");

System.out.println(result);

Result:

https://example.com/test?abc=**************567890123456&mnr=12345678901234567890123456

For more beautiful solution you can use this regex:

(?<=abc=[0-9]{0,14})[0-9](?=[0-9]{6})

And replacing will be:

String data = "https://example.com/test?abc=12345678901234567890123456&mnr=12345678901234567890123456";

String result = data.replaceAll("(?<=abc=[0-9]{0,14})[0-9](?=[0-9]{6})", "*");

System.out.println(result);

Result:

https://example.com/test?abc=***************67890123456&mnr=12345678901234567890123456

Upvotes: 0

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You can try this:

abc=\d{20}

and replace by this:

abc=********************

Demo

But if you want to validate if abc= followed by 20 digits and then 6 digits and then &mnr and then want to replace the first 20 digits of abc then you may use this regex:

abc=\d{20}(?=\d{6}&mnr)

Demo 2

if abc is followed by anything other than digit and you also want to address that, then you may try this:

replace \d{20} by \.{20}

Upvotes: 2

Related Questions