我需要能够替换出现在单引号之间的所有单词“and”。例如将字符串中的“and”替换为“XXX”:
这个和那个“与你和我以及其他人”而不是“她和他”
结果:
这个和那个“和你 XXX 我 XXX 其他人”而不是“她 XXX 他”
我已经能够想出几乎适用于所有情况的正则表达式,但是我在两组引用文本之间的“和”失败了。
我的代码:
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);
最佳答案
试试这段代码:
str = "This and that 'with you and me and others' and not 'her and him'";
Matcher matcher = Pattern.compile("('[^']*?')").matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).replaceAll("and", "XXX"));
}
matcher.appendTail(sb);
System.out.println("Output: " + sb);
输出
Output: This and that 'with you XXX me XXX others' and not 'her XXX him'
关于java - 如何替换引号之间出现的任何单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5888124/