RegEx Search and Replace in Java

July 7, 2016

I wanted to remove the contents of any tags in my XML that ended with the word Password, and replace the password with stars. So:

<xml>
  <password>ABC123</password>
  <securityPassword>sekr1t</securityPassword>
  <username>FRED</username>
</xml>

should turn into

<xml>
  <password>**</password>
  <securityPassword>**</securityPassword>
  <username>FRED</username>
</xml>

This can be done with regular expressions in Java like this:

String lMask = "$1**$3$4$5";
Pattern lPattern = Pattern.compile("(PASSWORD>)(.*?)(<\\/)(.*?)(PASSWORD>)", Pattern.CASE_INSENSITIVE);

  Matcher lMatcher = lPattern.matcher(lXml);
  StringBuffer lPasswordlessXml = new StringBuffer();
  while (lMatcher.find())
  {
    lMatcher.appendReplacement(lPasswordlessXml, lMask);
  }
  lMatcher.appendTail(lPasswordlessXml);