Java Regular Expression to mask information from a Text

This tutorial shows you how to mask information from a Text using Regular expression.

Related articles:
Java Regular Expression Overview – Syntax
Java Regular Expression to extract data from a Text

I. Problem

Assume that we already have a string that contains User data like this:

What we need is to mask sensitive users’ information using Regular Expression.

II. Practice

We have to make our own pattern to find and replace it from input text.
There are many ways to do this, for more details for how to choose syntax for the string pattern, please read this article: Java Regular Expression Overview – Syntax.
In this case, we can create a pattern like this:

You can see that we have 4 groups, the data we will mask are only in the 2nd group and 4th group.
So the Java code should be similar to:

To do that thing, we use 2 methods:

III. Source code

Run the code, the result shows in console window:

By grokonez | February 8, 2017.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *