唯一可靠的方法是搜索完整的引用序列或搜索词。您使用一个正则表达式来执行此操作,并在每次匹配后确定您匹配的是哪一个。如果是搜索词,则替换它;否则你别管它。
这意味着你不能使用replaceAll()
. 相反,您必须像它本身一样使用appendReplacement()
andappendTail()
方法。replaceAll()
这是一个例子:
String s = "Replace this example. Don't replace \"this example.\" Replace this example.";
System.out.println(s);
Pattern p = Pattern.compile("\"[^\"]*\"|(\\bexample\\b)");
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find())
{
if (m.start(1) != -1)
{
m.appendReplacement(sb, "REPLACE");
}
}
m.appendTail(sb);
System.out.println(sb.toString());
输出:
Replace this example. Don't replace "this example." Replace this example.
Replace this REPLACE. Don't replace "this example." Replace this REPLACE.
在线查看演示
我假设每个引号都很重要并且它们不能被转义——换句话说,你使用的是散文,而不是源代码。可以处理转义引号,但它会使正则表达式变得非常复杂。
如果您真的必须使用replaceAll()
,则有一个技巧,您可以使用前瞻来断言匹配后跟偶数个引号。但它真的很难看,而且对于大文本,你可能会发现它非常昂贵,性能方面。