Search code examples
javaregexreplaceall

Replacing a string as long it's not followed by another in java?


I have taken a whole file of code and placed it into a string: content. I need to replace all the words (class names) that start with A01 except those with A01Data and A01PrimaryFile with the name without the A01. (e.g. A01Numbers becomes Numbers I have tried:

content = content.replaceAll("A01(?!Data)|A01(?!PrimaryFile)", "");

but still the A01 gets taken away. Is there a better way to do this?

Thanks!


Solution

  • Put the | in the negative lookahead:

    content = content.replaceAll("A01(?!Data|PrimaryFile)", "");
    

    Think about it - your nonworking code checks for either A01 without Data in front, or A01 without PrimaryFile in front. The A01 can't have both in front at the same time, so it's always true.

    In this code, it checks for A01 with neither Data nor PrimaryFile in front.