ReplaceAll with Backreferences

From EggeWiki

Jump to: navigation, search

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.

        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);

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

assertEquals("RegexTest", this.getClass().getName().replaceAll("(?:\\w+\\.)*(\\w+)", "$1"));
Personal tools
Travelling Salesman

Get the app!