ReplaceAll with Backreferences

From EggeWiki
Revision as of 22:40, 8 October 2009 by Brianegge (talk | contribs) (Created page with '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 n…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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>