Regex using Java String.replaceAll
Asked Answered
S

3

10

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?

Suboxide answered 31/5, 2013 at 21:12 Comment(6)
what do you mean by not working?Scab
Remove the square brackets ([ and ]). These are for character classes. If something else is not working, you'll need to be more specific.Mercola
Are you aware of what a character class is in a regex? regex.infoBoysenberry
Strings are immutable.Emulsify
and Ignore Case modifier would work for a lot of the dept replacesIdiolect
As @Emulsify has pointed out: Strings are immutable. Your code will do nothing if you don't store the return value of String.replaceAll() somewhere. Right now your code does nothing with the return value.Orvieto
A
14

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;
}
Anthemion answered 31/5, 2013 at 21:53 Comment(2)
Instead of Pattern, we now have Matcher objects created every time. How is this better?Curet
Because compiling a regex Pattern is more costly than creating a Matcher for a (pre-compiled) Pattern?Punak
H
9
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.

Hassock answered 31/5, 2013 at 21:14 Comment(0)
E
3

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".

Equuleus answered 31/5, 2013 at 21:22 Comment(2)
+1 your answer is pretty good, but why the non-capturing group for "the "? Is it just "performance"? Cos IMHO readability drops more than performance increases. Btw I suspect /n is meant to be \nCleora
I'm just used to doing it like this. I never use capturing parentheses unless I want to capture a group. I agree that there's tension between stating one's intentions clearly and readability.Equuleus

© 2022 - 2024 — McMap. All rights reserved.