如何从存储在Ant属性中的文件路径中删除前缀?

时间:2012-08-23 23:03:10

标签: regex ant

我在Ant属性中有一个文件路径,例如/repo/java/projects/myproj。如何删除/repo/java并将结果projects/myproj存储在另一个属性中?

1 个答案:

答案 0 :(得分:4)

pathconvert Ant任务可以与嵌套mapper一起使用,以从路径中删除前两个目录(或获取前两个目录)。

删除前缀/repo/java/

匹配'/'文件分隔符

<property name="path" value="/repo/java/projects/myproj"/>

<target name="test1">
  <pathconvert property="path.fragment" pathsep="${line.separator}">
    <propertyresource name="path" />
    <mapper type="regexp"
        from="^/[^/]+/[^/]+/(.*)"
        to="\1"/>
  </pathconvert>
  <echo message="${path.fragment}" />
</target>

<强>输出

test1:
     [echo] projects/myproj

BUILD SUCCESSFUL
Total time: 0 seconds

匹配平台文件分隔符

<property name="path" value="/repo/java/projects/myproj"/>

<target name="test2">
  <pathconvert property="path.fragment" pathsep="${line.separator}">
    <propertyresource name="path" />
    <mapper type="regexp"
        from="^${file.separator}[^${file.separator}]+${file.separator}[^${file.separator}]+${file.separator}(.*)"
        to="\1"/>
  </pathconvert>
  <echo message="${path.fragment}" />
</target>

<强>输出

test2:
     [echo] projects/myproj

BUILD SUCCESSFUL
Total time: 0 seconds

获取前缀/repo/java/

匹配'/'文件分隔符

<property name="path" value="/repo/java/projects/myproj"/>

<target name="test3">
  <pathconvert property="path.fragment" pathsep="${line.separator}">
    <propertyresource name="path" />
    <mapper type="regexp"
        from="^(/[^/]+/[^/]+/).*"
        to="\1"/>
  </pathconvert>
  <echo message="${path.fragment}" />
</target>

<强>输出

test3:
     [echo] /repo/java/

BUILD SUCCESSFUL
Total time: 0 seconds

匹配平台特定文件分隔符

<property name="path" value="/repo/java/projects/myproj"/>

<target name="test4">
  <pathconvert property="path.fragment" pathsep="${line.separator}">
    <propertyresource name="path" />
    <mapper type="regexp"
        from="^(${file.separator}[^${file.separator}]+${file.separator}[^${file.separator}]+${file.separator}).*"
        to="\1"/>
  </pathconvert>
  <echo message="${path.fragment}" />
</target>

<强>输出

test4:
     [echo] /repo/java/

BUILD SUCCESSFUL
Total time: 0 seconds