Q:

Replace all odd occurrences of a substring using regex

I have a string ~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~
I want to replace the odd occurrences of substring '~~' i.e 1st, 3rd.. with another string '**'.  
My output should be **40~~ Celsius Temp: 33 Celsius Temp:**50~~
How to achieve this with regex in Java? 

A:

You really need a rudimentary parser to handle this; regex wasn't designed to count occurrences like this.   The logic of the code below is simple.   Every time we hit a match ~~ we do one of two things.   If it is an odd occurrence, then we append empty string to the replacement, otherwise we reappend the ~~ which we matched. 
String input = "~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~";
Pattern p = Pattern.compile("~~");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer(input.length());
int i = 0;

while (m.find()) {
    if (i % 2 == 0) {
        m.appendReplacement(sb, "**");
    }
    else {
        m.appendReplacement(sb, m.group(0));
    }
    ++i;
}
m.appendTail(sb);
System.out.println(sb.toString());

**40~~ Celsius Temp: 33 Celsius Temp:**50~~

Demo

