Jump to content

ReplaceAll with Backreferences

From EggeWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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>