encode42
encode42

Reputation: 55

Keep the same case when replacing words in Java

My goal is to correct common grammar errors in messages. Here's what I currently have written:

@EventHandler
public void onChat(AsyncPlayerChatEvent event){
    String message = event.getMessage().replaceAll("(?i)dont", "don't")
            .replaceAll("(?i)youre", "you're");

    event.setMessage(message);
}

This works to replace dont with don't, and youre with you're. The issue is that DONT is replaced with don't, rather than DON'T.

How would I execute this replacement while preserving case?

Upvotes: 0

Views: 91

Answers (1)

kaya3
kaya3

Reputation: 51037

Use capturing groups:

> "DoNt".replaceAll("(?i)\\b(don)(t)\\b", "$1'$2")
"DoN't" (String)

> "YoUrE".replaceAll("(?i)\\b(you)(re)\\b", "$1'$2")
"YoU'rE" (String)

You should also use \b for a word boundary, so you don't inadvertently change words like "orthodontist" into "orthodon'tist".

Upvotes: 5

Related Questions