How to replace any occurrence of a word between quotes

I need to be able to replace all occurrences of the word "and" ONLY when it occurs between single quotes. For example replacing "and" with "XXX" in the string:

This and that 'with you and me and others' and not 'her and him'

Results in:

This and that 'with you XXX me XXX others' and not 'her XXX him'

I have been able to come up with regular expressions which nearly gets every case, but I'm failing with the "and" between the two sets of quoted text.

My code:

String str = "This and that 'with you and me and others' and not 'her and him'";

String patternStr = ".*?\\'.*?(?i:and).*?\\'.*";
Pattern pattern= Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.matches());
while(matcher.matches()) {
    System.out.println("in matcher");
    str = str.replaceAll("(?:\\')(.*?)(?i:and)(.*?)(?:\\')", "'$1XXX$2'");
    matcher = pattern.matcher(str);
}

System.out.println(str);
5
задан Alan Moore 4 May 2011 в 18:29
поделиться