user2072797
user2072797

Reputation: 161

Regex using Java String.replaceAll

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?

Upvotes: 10

Views: 78791

Answers (3)

Paul Vargas
Paul Vargas

Reputation: 42060

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;
}

Upvotes: 14

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

You should read a basic regular expressions tutorial.

Until then, what you tried to do can be done like this:

cleanInst = cleanInst.replace("//", "/");
cleanInst = cleanInst.replaceAll("</?i>", "");
cleanInst = cleanInst.replaceAll("/n\\b", ";")
cleanInst = cleanInst.replaceAll("\\bPhysics Dept\\.", "Physics Department");
cleanInst = cleanInst.replaceAll("(?i)\\b(?:the )?dept\\b\\.?", "The Department");

You could probably chain all those replace operations (but I don't know the proper Java syntax for this).

About the word boundaries: \b usually only makes sense directly before or after an alphanumeric character.

For example, \b/n\b will only match /n if it's directly preceded by an alphanumeric character and followed by a non-alphanumeric character, so it matches "a/n!" but not "foo /n bar".

Upvotes: 3

Eng.Fouad
Eng.Fouad

Reputation: 117675

cleanInst.replaceAll("[<i>]", "");

should be:

cleanInst = cleanInst.replaceAll("[<i>]", "");

since String class is immutable and doesn't change its internal state, i.e. replaceAll() returns a new instance that's different from cleanInst.

Upvotes: 9

Related Questions