Regular Expression Replacement in an Ant Property

I’m quite a newbie in Ant, but I thought it would be straightforward to do a regular expression replacement in a string contained in a property; in my case, I had to replace Windows backslashes with Unix slashes… apparently, unless you use the propertyregex task from Ant Contrib, that is not supported out-of-the-box: you have to pass through a file!

This stackoverflow post shows a possible solution, and starting from that, I created a macrodef to make it easier

<!-- = = = = = = = = = = = = = = = = =
  macrodef: replace_win_slashes          
 = = = = = = = = = = = = = = = = = -->
<macrodef name="replace_win_slashes">
	<attribute name="property.to.process" default="default" />
	<attribute name="output.property" default="default" />
	<sequential>
		<echo message="@{property.to.process}" file="some.tmp.file" />
		<loadfile property="@{output.property}" srcFile="some.tmp.file">
			<filterchain>
				<tokenfilter>
					<replaceregex pattern="\\" replace="/" flags="g" />
				</tokenfilter>
			</filterchain>
		</loadfile>
		<delete file="some.tmp.file" />
	</sequential>
</macrodef>

This macro takes the property value to process (property.to.process) and the property name where to store the result; it outputs the input value to a temporary file, reads it back with a regular expression replacement (which is supported for files) and store it in the specified property (the temporary file is then deleted).

Here’s an example of use

<project name="replace win slashes" >
	<property name="my.prop1" value="file:C:\Users\bettini/my/path1" />

	<!-- = = = = = = = = = = = = = = = = =
          macrodef: replace_win_slashes          
         = = = = = = = = = = = = = = = = = -->
	<macrodef name="replace_win_slashes">
		<attribute name="property.to.process" default="default" />
		<attribute name="output.property" default="default" />
		<sequential>
			<echo message="@{property.to.process}" file="some.tmp.file" />
			<loadfile property="@{output.property}" srcFile="some.tmp.file">
				<filterchain>
					<tokenfilter>
						<replaceregex pattern="\\" replace="/" flags="g" />
					</tokenfilter>
				</filterchain>
			</loadfile>
			<delete file="some.tmp.file" />
		</sequential>
	</macrodef>

	<replace_win_slashes property.to.process="${my.prop1}" output.property="my-prop-1" />

	<echo message="my-prop-1 = ${my-prop-1}" />

</project>

 

Be Sociable, Share!

3 thoughts on “Regular Expression Replacement in an Ant Property

Leave a Reply