|
10.3. Subtituting Text Using Regular ExpressionsThe replaceregexp task can replace every occurrence of a given regular expression with a substitution pattern in a selected file or set of files.
Example 10-2 uses replaceregexp, where text in the XML comment in the build file matching "Here's a comment." is converted to "Here's an XML comment." Example 10-2. Using regular expression substitutions (ch10/regexp/build.xml)<?xml version="1.0"?> <project default="main" basedir="."> <!--Here's a comment.--> <target name="main"> <replaceregexp match="a comment" replace="an XML comment"> <fileset dir="." includes="**/*.xml" /> </replaceregexp> </target> </project> Here's what the build file looks like after you run it: <?xml version="1.0"?> <project default="main" basedir="."> <!--Here's an XML comment.--> <target name="main"> <replaceregexp match="a comment" replace="an XML comment"> <fileset dir="." includes="**/*.xml" /> </replaceregexp> </target> </project> Changing the contents of other files this way will be useful if you need to rewrite build files that you're about to call with the ant task. Here's an example of editing build files to convert from a local to an FTP install: <?xml version="1.0"?> <project default="main" basedir="."> <target name="main"> <replaceregexp match="<copy file='Project.jar' todir='dist'/>" replace="<ftp server='ftp.isp.com'><fileset dir='bin'/></ftp>" <fileset dir="subproject" includes="**/*.xml" /> </replaceregexp> </target> <ant dir="subproject"/> </project>
Here's another example, this time of replacing all whitespace in documentation files with spaces: <replaceregexp match="\s+" replace=" " flags="g"> <fileset dir="docs" includes="**/*.html" /> </replaceregexp> The attributes of this task appear in Table 10-3.
This task supports a nested fileset element. You can use a nested regexp element to specify the regular expression this way: <regexp pattern="\s+"/> <regexp ref/> The replaceregexp task supports a nested substitution element to specify the substitution pattern; here are some examples: <substitution expression="beta\1alpha"/> <substitution ref/> |
|