3

我试图替换文件中出现的单词,除非它包含在字符串中:

this所以我应该更换

The test in this line consists in ... 

但不应该匹配:

The test "in this line" consist in ... 

这就是我正在尝试的:

 line.replaceAll( "\\s+this\\s+", " that ")

但是在这种情况下它失败了,所以我尝试使用:

 line.replaceAll( "[^\"]\\s+this\\s+", " that ")

但也不起作用。

任何帮助,将不胜感激

4

2 回答 2

3

这似乎有效(就我从提供的示例中了解您的要求而言):

 (?!.*\s+this\s+.*\")\s+this\s+

http://rubular.com/r/jZvR4XEbRf

您可能需要调整 Java 的转义。

这实际上要好一些:

 (?!\".*\s+this\s+)(?!\s+this\s+.*\")\s+this\s+
于 2011-10-26T03:47:20.067 回答
2

唯一可靠的方法是搜索完整的引用序列或搜索词。您使用一个正则表达式来执行此操作,并在每次匹配后确定您匹配的是哪一个。如果是搜索词,则替换它;否则你别管它。

这意味着你不能使用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(),则有一个技巧,您可以使用前瞻来断言匹配后跟偶数个引号。但它真的很难看,而且对于大文本,你可能会发现它非常昂贵,性能方面。

于 2011-10-26T05:41:34.127 回答