lembas lembas - 2 months ago 11
Java Question

Correct the word "urgent" with repeated letters using regular expression in Java

I want to change "Hitttt Urrggeennnttt Rrare" with "Hitttt Urgent Rrare" using regex, or "Uupppp Uuurrggeent Upp!! Barrkk" with "Uupppp Urgent Upp!! Barrkk". (All words are in camel case.)

I mean I just want to correct the 'urgent's, not the other words.

s.replaceAll("([Urgent])\\1+", "$1");


does not work. Any idea?

Answer

This should work for you:

public static void main(String[] args) {
    String s = "hitttt Urrggeennnttt rrare";
    s = s.replaceAll("(?i)u+r+g+e+n+t+", "Urgent"); // ?i ==> case insensitive
    System.out.println(s);
}

hitttt Urgent rrare