Jugi
Jugi

Reputation: 1254

How to replace a string in a file based on a condition using ant

I want to replace a string in a file using ant. For example, i need to scan all the files in a directory to match the string "CHANGEME" and i achieved this using below code,

<replaceregexp dir="C:/sample" match='CHANGEME' replace='XXX' flags="gi" byline="true" />

Now the string should not be changes if it contains any special character like "CHANGEME?". Can anyone suggest how to handle this condition in replaceregexp ant task ?

Upvotes: 1

Views: 1282

Answers (1)

CAustin
CAustin

Reputation: 4614

This can be accomplished with the regex pattern itself. You don't need to create a condition in Ant.

Also, note that the dir attribute is not supported by the replaceregexp task. You'll need to use a nested resource collection if you want to run the replacement on multiple files.

<replaceregexp match="CHANGEME(?!\p{P})" replace="XXX" flags="gi" byline="true">
    <fileset dir="C:/sample" includes="**/*" />
</replaceregexp>

Explanation of (?!\p{P}):

(?! ... ) - Negative lookahead. The preceding pattern ("CHANGEME") will only successfully match if the pattern contained in these parentheses does not follow it.

\p{P} - Unicode category for punctuation characters. You didn't specify exactly which characters should be considered "special characters", but this should cover most of them. Let me know if you have any outliers and I'll edit the answer accordingly.

Upvotes: 3

Related Questions