0

How do I replace comma and right parantheses at the same time, ,') with ), in groovy? I tried replaceAll with double escape

value = "('cat','rat',',')";
//Replace  ,')  with )
value = value.replaceAll('\\,')',')');

Tried these with no luck How can I replace a string in parentheses using a regex?

How to escape comma and double quote at same time for CSV file?

Community
  • 1
  • 1
lonelymo
  • 3,972
  • 6
  • 28
  • 36
  • Try [`value.replaceAll("(,|^)','", "")`](http://ideone.com/9vKmGs) if you want to remove all values equal to `','` both from the start of the string and inside it. – Wiktor Stribiżew Sep 06 '16 at 21:55

1 Answers1

2

Your question is a bit cofusing, but to replace ,') you don't need escapes at all. Simply use

def value = "('cat','rat',',')";
println value.replace(",')", ")"); // ('cat','rat',')

However, I think you rather want this result ('cat','rat'). Right?

If so, you can use the following code, using Pattern:

import java.util.regex.Pattern

def value = "('cat','rat',',')";
def pattern = Pattern.compile(",'\\)");
def matcher = pattern.matcher(value);
while (matcher.find()) {
    value = matcher.replaceAll(")");
    matcher = pattern.matcher(value);
}
println value; // ('cat','rat')

Explanation:

You are creating the second replaceable text with your regex, it's not there when you try to replace it, but get's created as a result of the first replacement. So we create a new matcher in the loop and let it find the string again...

baao
  • 71,625
  • 17
  • 143
  • 203