Search code examples
javaregexreplaceall

Replace a word that is not on a string


I'm trying to replace a word in a file whenever it appears except when it is contained in a string:

So I should replace this in

The test in this line consists in ... 

But should not match in :

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

This is what I'm trying:

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

But it fails with this scenario so I tried using:

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

But doesn't work either.


Solution

  • This seems to work (in so far as I understand your requirements from the examples provided):

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

    http://rubular.com/r/jZvR4XEbRf

    You may need to adjust the escaping for java.

    This is a bit better actually:

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