How to do Pattern based Search in String and replace with another in Java

In our day today life we have faced some challenges like, to replace the particular pattern (String) by some other string. In this scenario we could use the Pattern matcher with regular expressions. Let’s see how we could achieve it.

Our input string is,

String inputStr = "Every week here and in our newsletter, 143-37-8945 we feature a new developer/blogger from the DZone community to catch up and find out what243-45-3442 he or she is working";

In this above String I want to find the numbers like this 143-37-8945 & 243-45-3442 and mask the last 4 digits.

Now we have to form a regular expression like as below,

(\\d{3}-\\d{2}-\\d{4})

Then we have to match the pattern with input string and find the pattern XXX-XX-XXXX, then have to mask it.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternSearch {
public static void main(String[] args) {

// Input string.
String inputStr = "Every week here and in our newsletter, 143-37-8945 we feature a new developer/blogger from the DZone community to catch up and find out what243-45-3442 he or she is working";

// Regular expression to find SSN.
Pattern pattern = Pattern.compile("(\\d{3}-\\d{2}-\\d{4})");

Matcher matcher = pattern.matcher(inputStr);

StringBuffer result = new StringBuffer();

// Every match of SSN, this loop will execute.
while (matcher.find()) {
System.out.println(matcher.group(1));
matcher.appendReplacement(result, matcher.group(1).substring(0, 7)
+ "XXXX");
}
matcher.appendTail(result);
System.out.println(result);
}
}

Output:

143-37-8945

243-45-3442

Every week here and in our newsletter, 143-37-XXXX we feature a new developer/blogger from the DZone community to catch up and find out what243-45-XXXX he or she is working.

Happy Learning!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: