user7128116
user7128116

Reputation:

Replace characters in a String, in a specific location

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?

Upvotes: 0

Views: 43

Answers (2)

infiniteRefactor
infiniteRefactor

Reputation: 2120

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.

Upvotes: 1

Alfakyn1
Alfakyn1

Reputation: 83

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.

Upvotes: 0

Related Questions