如何在Ant中提取子字符串

Lar*_*ark 34 ant

有没有办法从Ant属性中提取子字符串并将该子字符串放入其自己的属性中?

小智 36

我使用scriptdef为substring创建一个javascript标记,例如:

 <project>
  <scriptdef name="substring" language="javascript">
     <attribute name="text" />
     <attribute name="start" />
     <attribute name="end" />
     <attribute name="property" />
     <![CDATA[
       var text = attributes.get("text");
       var start = attributes.get("start");
       var end = attributes.get("end") || text.length();
       project.setProperty(attributes.get("property"), text.substring(start, end));
     ]]>
  </scriptdef>
  ........
  <target ...>
     <substring text="asdfasdfasdf" start="2" end="10" property="subtext" />
     <echo message="subtext = ${subtext}" />
  </target>
 </project>
Run Code Online (Sandbox Code Playgroud)


Ins*_*oup 22

您可以尝试使用Ant-Contrib的PropertyRegex.

   <propertyregex property="destinationProperty"
              input="${sourceProperty}"
              regexp="regexToMatchSubstring"
              select="\1"
              casesensitive="false" />
Run Code Online (Sandbox Code Playgroud)


小智 10

由于我更喜欢​​使用vanilla Ant,因此我使用临时文件.无处不在,你可以利用replaceregex来摆脱你想要的字符串部分.重置Git消息的示例:

    <exec executable="git" output="${git.describe.file}" errorproperty="git.error" failonerror="true">
        <arg value="describe"/>
        <arg value="--tags" />
        <arg value="--abbrev=0" />
    </exec>
    <loadfile srcfile="${git.describe.file}" property="git.workspace.specification.version">
        <filterchain>
           <headfilter lines="1" skip="0"/>
           <tokenfilter>
              <replaceregex pattern="\.[0-9]+$" replace="" flags="gi"/>
           </tokenfilter>
           <striplinebreaks/>
        </filterchain>
    </loadfile>
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在处理一个属性,可以通过执行类似<loadresource> <concat> $ {property.here} </ concat> <filterchain> <replaceregex pattern ="*eek"/>的方式来避开该文件. </ filterchain> </ loadresource> (5认同)

Mar*_*lof 6

我想一个简单的香草方法是:

<loadresource property="destinationProperty">
    <concat>${sourceProperty}</concat>
    <filterchain>
        <replaceregex pattern="regexToMatchSubstring" replace="\1" />
    </filterchain>
</loadresource>
Run Code Online (Sandbox Code Playgroud)