Hadi Hassan
Hadi Hassan

Reputation: 31

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.

Upvotes: 2

Views: 56

Answers (2)

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

Remove the [] and write .replaceAll("OB(?=[AaEeIiOoUu])", "");.

[] means match anything inside [] individually

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163217

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

Upvotes: 1

Related Questions