I am looking to replace a java string value as follows. below code is not working.
cleanInst.replaceAll("[<i>]", "");
cleanInst.replaceAll("[</i>]", "");
cleanInst.replaceAll("[//]", "/");
cleanInst.replaceAll("[\bPhysics Dept.\b]", "Physics Department");
cleanInst.replaceAll("[\b/n\b]", ";");
cleanInst.replaceAll("[\bDEPT\b]", "The Department");
cleanInst.replaceAll("[\bDEPT.\b]", "The Department");
cleanInst.replaceAll("[\bThe Dept.\b]", "The Department");
cleanInst.replaceAll("[\bthe dept.\b]", "The Department");
cleanInst.replaceAll("[\bThe Dept\b]", "The Department");
cleanInst.replaceAll("[\bthe dept\b]", "The Department");
cleanInst.replaceAll("[\bDept.\b]", "The Department");
cleanInst.replaceAll("[\bdept.\b]", "The Department");
cleanInst.replaceAll("[\bdept\b]", "The Department");
What is the easiest way to achieve the above replace?
If it is a function that continuously you are using, there is a problem. Each regular expression is compiled again for each call. It is best to create them as constants. You could have something like this.
private static final Pattern[] patterns = {
Pattern.compile("</?i>"),
Pattern.compile("//"),
// Others
};
private static final String[] replacements = {
"",
"/",
// Others
};
public static String cleanString(String str) {
for (int i = 0; i < patterns.length; i++) {
str = patterns[i].matcher(str).replaceAll(replacements[i]);
}
return str;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With