如何在引号之间替换任何单词的出现

时间:2011-05-04 18:23:58

标签: java regex

我需要能够替换所有出现的单词"和"仅当它出现在单引号之间时。例如,替换"和"用" XXX"在字符串中:

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

结果:

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

我已经能够提出几乎适用于所有情况的正则表达式,但是我没有使用"和#34;在两组引用文本之间。

我的代码:

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);

2 个答案:

答案 0 :(得分:6)

试试这段代码:

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'

答案 1 :(得分:2)

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

Pattern p = Pattern.compile("(\\s+)and(\\s+)(?=[^']*'(?:[^']*+'[^']*+')*+[^']*+$)");
System.out.println(p.matcher(str).replaceAll("$1XXX$2"));

这个想法是,每当你找到完整的单词and时,你就会从当前的匹配位置扫描到字符串的结尾,寻找奇数个单引号。如果前瞻成功,匹配的单词必须在一对引号之间。

当然,这假设引号总是匹配对,并且引号无法转义。可以处理使用反斜杠转义的行情,但它会使正则表达式更长。

我还假设目标词永远不会出现在引用序列的开头或结尾,这对单词and来说似乎是合理的。如果你想允许包围空格的目标词,你可以使用类似"\\band\\b"的东西,但要注意word characters vs word boundaries区域中的Java问题。