I want to replace certain substrings with a replacement, both defined within a Hashmap. An example is the following:
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
private static HashMap<String, String> conversionTable;
public static void main(String[] args) {
initConversionTable();
System.out.println(convertNumbers("la1"));
System.out.println(convertNumbers("la1, lb3"));
}
private static String convertNumbers(String text) {
String regex = "([aub][1-3])";
Matcher m = Pattern.compile(regex).matcher(text);
while(m.find()) {
text = m.replaceAll(conversionTable.get(m.group()));
}
return text;
}
private static void initConversionTable() {
conversionTable = new HashMap<>();
conversionTable.put("a1", "A1");
conversionTable.put("a2", "A2");
conversionTable.put("a3", "A3");
conversionTable.put("u1", "U1");
conversionTable.put("u2", "U2");
conversionTable.put("u3", "U3");
conversionTable.put("b1", "B1");
conversionTable.put("b2", "B2");
conversionTable.put("b3", "B3");
}
}
For input data
la1
la1, lb3
The expected result should be
lA1
lA1, lB3
but is
lA1
lA1, lA1
Until now I have not succeeded finding a solution with a Matcher. Is there such a solution? Of course I could go through each Entry of the HashMap and do the replacement, but I would like to solve it with a Matcher, because I fear that for a very long Hashmap and many strings this could influence the performance.
Thank you very much!