【问题标题】:In Ant, how can I test if a property ends with a given value?在 Ant 中,如何测试属性是否以给定值结尾?
【发布时间】:2012-11-30 17:05:33
【问题描述】:

在 Ant 中,如何测试属性是否以给定值结尾?

例如

 <property name="destdir" 
     value="D:\FeiLong Soft\Essential\Development\repository\org\springframework\spring-beans" />

如何测试${destdir} 是否以"spring-beans" 结尾?

补充:

在我的 ant-contrib-1.0b3.jar 中,没有 'endswith' 任务~~

【问题讨论】:

    标签: ant ant-contrib


    【解决方案1】:

    您可以测试 ${destdir} 是否像这样以“spring-beans”结尾(假设您有 ant-contrib,并且使用的是 Ant 1.7 或更高版本)。

    <property name="destdir" value="something\spring-beans" />
    <condition property="destDirHasBeans">
      <matches pattern=".*spring-beans$" string="${destdir}" /> 
    </condition>
    <if>
      <equals arg1="destDirHasBeans" arg2="true" />
      <then>
          $destdir ends with spring-beans ...
      </then>
      <else> ...
      </else>
    </if>
    

    正则表达式模式".*spring-beans$" 中的“$”是匹配字符串末尾的锚点。

    【讨论】:

      【解决方案2】:

      作为Matteo,Ant-Contrib 包含很多好东西,我大量使用它。

      但是,在这种情况下可以简单地使用&lt;basename&gt; 任务:

      <basename property="basedir.name" file="${destdir}"/>
      <condition property="ends.with.spring-beans">
         <equals arg1="spring-beans" arg2="${basedir.name}"/>
      <condition>
      

      如果${destdir}string-beans 结尾,则属性${ends.with.spring-beans} 将包含true,否则将包含false。您可以在&lt;target&gt; 任务的ifunless 参数中使用它。

      【讨论】:

      • 这用于测试路径的最后一个组件是否等于“spring-beans”。测试属性是否严格以该子字符串结尾是行不通的。
      【解决方案3】:

      您可以使用Ant-Contrib 中的EndWith 条件

      <endswith string="${destdir}" with="spring-beans"/>
      

      例如

      <if>
          <endswith string="${destdir}" with="spring-beans"/>
          <then>
              <!-- do something -->
          </then>
      </if>
      

      编辑

      &lt;endswith&gt; 是 Ant-Contrib 包的一部分,必须安装并启用

      <taskdef resource="net/sf/antcontrib/antlib.xml"/>
      

      【讨论】:

      【解决方案4】:

      JavaScript 的强大功能可用于 ANT 中的字符串操作:

      <script language="javascript"> <![CDATA[
      
              // getting the value for property sshexec.outputproperty1
              str = project.getProperty("sshexec.outputproperty1");
      
              // get the tail , after the separator ":"
             str = str.substring(str.indexOf(":")+1,str.length() ).trim();
      
              // store the result in a new property
              project.setProperty("res",str);
      
      
          ]]> </script>
      <echo message="Responce ${res}" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-09
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多