Anyway, this doesn't mean that it's not possible to achieve the same effect on texts. Actually there are at least two ways: the first is to use AntContrib's <PropertyRegex> task. The second (that works only starting from Ant 1.7.1) is to combine some standard Ant task to do the same: just read on.
Let's start from the <concat> task. The documentation says: "Since Ant 1.7.1, this task can be used as a Resource Collection that will return exactly one resource". Moreover "since Ant 1.6 it supports nested FilterChains". This is important because FilterChains are formed also by TokenFilters and a TokenFilter can be a ReplaceRegex string filter. Confused? Take a look at the following code:
<macrodef name="replaceStringWithRegExp">Here I've defined a macro named "replaceStringWithRegExp". It takes four input parameters:
<attribute name="string"/>
<attribute name="searchPattern"/>
<attribute name="replacementPattern"/>
<attribute name="property"/>
<sequential>
<tokens id="id">
<concat>
<string value="@{string}"/>
<filterchain>
<tokenfilter>
<replaceregex pattern="@{searchPattern}"
replace="@{replacementPattern}"
flags="g"/>
</tokenfilter>
</filterchain>
</concat>
</tokens>
<property name="@{property}" value="${toString:id}"/>
</sequential>
</macrodef>
- string: text to match against a regular expression
- searchPattern: regular expression
- replacementPattern: substitution pattern
- property: name for a new property that will contain the result of the replacement
To extract the result of <concat> task, I've wrapped this task around a <tokens> task and I've assigned an id to the external task. Finally, using the expression ${toString:id} it's possible to extract the toString value from the <tokens> task: this is the result of the search and replacement. Pretty tricky, isn't it?
Now let's try it.
<replaceStringWithRegExp string="James Bond"Here we get: "My name is Bond, James Bond". Well, it works.
searchPattern="(\w+)\s+(\w+)"
replacementPattern="My name is \2, \1 \2"
property="result"/>
<echo message="${result}"/>
1 comment:
if your using maven and want regex text replacement, check out maven-replacer-plugin rather than using ant inside of maven
Post a Comment