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?

3
  • suppose this post is about getting the words inside quotes. Commented Apr 20, 2017 at 23:58
  • what do you want to replace it with? Commented Apr 20, 2017 at 23:58
  • Anything, for example * Commented Apr 21, 2017 at 0:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is a good answer. If you change the regexp from \"(.*)\" to \"([^\"]*)\", it will work for multiple pairs of quotes also.
@msandiford I used .*? (reluctant matcher), that does the same thing.
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.

2 Comments

Nop, i'm not sure if the "," is the last, thanks for the help.
then look for "day," instead of only ","

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.