java – Regex to replace bind parameters that NOT in quotes

I have a regex that detects text in quotes (first group) and bind parameters (second group).
Group for text in quotes is required to avoid replacing bind parameters in it.

('[^\\n']*')|(:\\s*\\w+)

I tried to keep first group and replace second one with “?”:

public static String replaceBindVars(String value) {
    return value.replaceAll("('[^\\n']*')|(:\\s*\\w+)", "$1?"); 
}

The problem is that it adds “?” after first group.

Code to test, the result should be true in all cases:

public static void main(String[] args) {    
    System.out.println("WHERE id = ? and productcode = ?"
            .equals(replaceBindVars("WHERE id = :id and productcode = :product_code")));
    
    System.out.println("WHERE id = ? and productcode="1:2 :3""
            .equals(replaceBindVars("WHERE id = :id and productcode="1:2 :3"")));
    
    System.out.println("WHERE id = ? and code LIKE ': some-string with :colon and :bind_parameters' OR product_name LIKE ?'".
            equals(replaceBindVars("WHERE id = :id and code LIKE ': some-string with :colon and :bind_parameters' OR product_name LIKE :product_name'")));
    
    System.out.println("SELECT ? and ? WHERE id = 2 and product_code = 3".
            equals(replaceBindVars("SELECT :id and :product_code WHERE id = 2 and product_code = 3")));
    
}

Is there any way to modify my current regex to do not add “?” after bind parameters in quotes? Preferred Java version is 8.

I saw this similar question, but it doesn’t help.

Read more here: Source link