Search code examples
javaregexstringreplaceall

Remove the same occurrence of specific characters


I want to remove "OB" from the string that i put before every vowel. For example: "THIS IS SOME REALLY GREAT BOLD TEXT" & after adding OB to it: "THOBISOBISSOBOMOBEROBEOBALLYGROBEOBATBOBOLDTOBEXT" That is the method that i wrote.

public static String unObify(String param) {

    String deleteOB = param.replaceAll("[OB]", "");

    return deleteOB;

}

Output: THISISSMEREALLYGREATLDTEXT

but the problem is that this method also remove O and B inside my String. and i only want to remove OB which occurs one after the other.


Solution

  • With your current regex [OB], you specify a character class which matches O or B.

    If you want to replace OB before every vowel, you could use positive lookahead to assert what follows is a vowel:

    OB(?=[AEIOU])

    Or as @Tim Biegeleisen pointed out, use make the lookahead case insensitive:

    OB(?=(?i)[AEIOU](?-i)) or OB(?=[aeiouAEIOU])

    public static String unObify(String param) {
    
        String deleteOB = param.replaceAll("OB(?=[AEIOU])", "");
    
        return deleteOB;
    
    }
    

    That would replace

    THOBISOBISSOBOMOBEROBEOBALLYGROBEOBATBOBOLDTOBEXT to THISISSOMEREALLYGREATBOLDTEXT

    and

    THOBSOBISSOBOMOBEROBEOBALLYGROBEOBATBOBOLDTOBEXT to THOBSISSOMEREALLYGREATBOLDTEXT