I don’t think I’d use a regular expression for this. I am offering three avenues:
- The easy way: for each digit from 0 through 9, replace every occurrence.
- Build the result in a
StringBuilder. For each char in the original string append the appropriate word if it’s a digit, otherwise just the char.
- A fix to your regex approach.
Replace all digits
I have put your declaration outside the method (you don’t have to do that):
private static final String SINGLE_DIGITS[] = { "ZERO", "ONE", "TWO", "THREE",
"FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
Now we do:
String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
for (int d = 0; d < 10; d++) {
testString = testString.replace(String.valueOf(d), SINGLE_DIGITS[d]);
}
System.out.println(testString);
Output:
Hello I have two passwords with dkONETWOkdkd and TWOFIVEkdkaeFIVE.
When some digit is not found (for example, 0), replace() just returns the same string (or an equal one, I don’t care). If on the other hand a digit occurs more than once (both 2 and 5 do), every occurrence is replaced. This is not the most efficient way, but for strings the size of yours you should be fine.
Build result linearly
I am using these further declarations:
private static final BitSet DIGITS = new BitSet();
static {
DIGITS.set('0', '9' + 1);
}
Now we can do:
StringBuilder buf = new StringBuilder();
for (int ix = 0; ix < testString.length(); ix++) {
char ch = testString.charAt(ix);
if (DIGITS.get(ch)) {
buf.append(SINGLE_DIGITS[Character.getNumericValue(ch)]);
} else {
buf.append(ch);
}
}
String result = buf.toString();
System.out.println(result);
Output is the same as before. This is the recommended way if efficiency is a priority.
Your approach with regex
First, since you want 12 replaced by ONETWO(not TWELVE), don’t include a + in your regular expression:
public static Pattern pattern = Pattern.compile("\\d");
Now for each digit found, make a lookup in SINGLE_DIGITS to find the replacement:
Matcher matcher = pattern.matcher(testString);
while (matcher.find()) {
testString = testString.replace(matcher.group(),
SINGLE_DIGITS[Integer.parseInt(matcher.group())]);
}
System.out.println(testString);
The output is the same as before.