替换不在字符串上的单词

时间:2011-10-26 03:31:24

标签: java regex replaceall

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

所以我应该替换

中的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 ")

但也不起作用。

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

这似乎有效(据我所知,从所提供的示例中了解您的要求):

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

http://rubular.com/r/jZvR4XEbRf

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

实际上这有点好:

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

答案 1 :(得分:2)

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

这意味着您无法使用replaceAll()。相反,您必须使用像appendReplacement()本身那样的appendTail()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.

See demo online

我假设每个引号都很重要且无法转义 - 换句话说,你正在使用散文,而不是源代码。可以处理转义引号,但它会使正则表达式大大复杂化。

如果你真的必须使用replaceAll(),那么一个技巧,你可以使用前瞻来断言匹配后跟偶数引号。但它真的很丑陋,对于大型文本,你可能会发现它在性能方面非常昂贵。