0

I have the following string;

String s = "Hellow world,how are you?\"The other day, where where you?\"";

And I want to replace the , but only the one that is inside the quotation mark \"The other day, where where you?\".

Is it possible with regex?

buræquete
  • 14,226
  • 4
  • 44
  • 89

2 Answers2

1
String s = "Hellow world,how are you?\"The other day, where where you?\"";
Pattern pattern = Pattern.compile("\"(.*?)\"");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    s = s.substring(0, matcher.start()) + matcher.group().replace(',','X') + 
            s.substring(matcher.end(), s.length());                                  
}

If there are more then two quotes this splits the text into in quote/out of quote and only processes inside quotes. However if there are odd number of quotes (unmatched quotes), the last quote is ignored.

infiniteRefactor
  • 1,940
  • 15
  • 22
0

If you are sure this is always the last "," you can do that

String s = "Hellow world,how are you?\"The other day, where where you?\"";
int index = s.lastIndexOf(",");
if( index >= 0 )
    s = new StringBuilder(s).replace(index , index + 1,"X").toString();
System.out.println(s);

Hope it helps.

Alfakyn1
  • 83
  • 3
  • 12