Pavan
Pavan

Reputation: 77

Have SSN masked in between the tags

I have this program

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        String subjectString = "<Name>DGAU</Name><SSN>123456789</SSN><OtherDetails></OtherDetails>";
        
        String REPLACE = "#";
        
        Pattern regex = Pattern.compile("<SSN>\\d{9}");
        Matcher regexMatcher = regex.matcher(subjectString);
        
        subjectString = regexMatcher.replaceAll(REPLACE);
        System.out.println(subjectString);
            
    }

}

When i run the above program

The Output formed is

<Name>DGAU</Name>#</SSN><OtherDetails></OtherDetails>

How to have output as

<Name>DGAU</Name><SSN>#</SSN><OtherDetails></OtherDetails>

Have the SSN # in between .

Upvotes: 0

Views: 39

Answers (1)

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Use Regex

(<SSN>)\d{9}

and replace it with

$1#

as shown here

Code

Explanation:

  • (<SSN>) - matches <SSN> and captures it in Group 1
  • \d{9} - matches 9 digits

Now replace the entire match with $1# i.e, contents of Group 1 followed by #

Note: In Java, you need to escape \ with another \. So, your regex is (<SSN>)\\d{9}

Upvotes: 3

Related Questions