ReplaceAll with Backreferences

From EggeWiki

Regex functions can give you fast replacements in Java, along with the readability of Perl. Here's an example of using a replaceAll to mask out certain digits in a credit card number.

<geshi lang="java5">

       String account = "1234567890123456";
       String replacement = account.replaceAll("(\\d{4})(\\d{2})(\\d{6})(\\d{4})", "$1 $2XX XXXX $4");
       assertEquals("1234 56XX XXXX 3456", replacement);

</geshi>

Another fun regex can simulate the the unix 'basename' function.

<geshi lang="java5"> assertEquals("RegexTest", this.getClass().getName().replaceAll("(?:\\w+\\.)*(\\w+)", "$1")); </geshi>