Sunday, June 20, 2010

Using regex to replace a digit with that many number of zeroes

This was an illustrative example I concocted to answer a stackoverflow question.

The problem: using one String.replaceAll, replace each digit with that many number of zeroes.
See also: [stackoverflow] -- Regex: how can I replace $n with n instances of a string?

It's not pretty, but this can in fact be done (see on ideone.com):
// meta-regexing to generate the regex and replacement string
String seq = "123456789";
String regex = "(?x)\n" + seq.replaceAll(".", "(?=[$0-9].*(0)\\$)?\n") + "[0-9]";
String repl = seq.replaceAll(".", "\\$$0");

// let's see what they look like!  
System.out.println(repl);
// $1$2$3$4$5$6$7$8$9
System.out.println(regex);
// (?x)
// (?=[1-9].*(0)$)?
// (?=[2-9].*(0)$)?
// (?=[3-9].*(0)$)?
// (?=[4-9].*(0)$)?
// (?=[5-9].*(0)$)?
// (?=[6-9].*(0)$)?
// (?=[7-9].*(0)$)?
// (?=[8-9].*(0)$)?
// (?=[9-9].*(0)$)?
// [0-9]

String input = "3 2 0 4 x 11 9";
System.out.println(
 (input + "0").replaceAll(regex, repl)
);
// 000 00  0000 x 00 000000000
// it works!  

Here's a bonus snippet that shows the same technique, applied differently (see also on ideone.com):
String seq = "123456789";
String regex = seq.replaceAll(".", "(?=[$0-9]([a-z]))?") + "[0-9][a-z]";
String repl = seq.replaceAll(".", "\\$$0");

String input = "3a 2b 0c 4d 5x";
System.out.println(input.replaceAll(regex, repl));
// aaa bb  dddd xxxxx

No comments:

Post a Comment