1

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 ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @CAustin. This is what i am looking for. Thanks for the solution. My scenario is if the string to be replaced contains question mark (?) after the string, it should not be replaced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.