string 替换 Ant 属性中的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1176071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:29:39  来源:igfitidea点击:

Replacing characters in Ant property

stringant

提问by aberrant80

Is there a simple way of taking the value of a property and then copy it to another property with certain characters replaced?

是否有一种简单的方法可以获取属性的值,然后将其复制到另一个替换了某些字符的属性?

Say propA=This is a value. I want to replace all the spaces in it into underscores, resulting in propB=This_is_a_value.

propA=This is a value。我想将其中的所有空格替换为下划线,导致propB=This_is_a_value.

采纳答案by Jon Skeet

Use the propertyregextask from Ant Contrib.

使用Ant Contrib 中propertyregex任务。

I think you want:

我想你想要:

<propertyregex property="propB"
               input="${propA}"
               regexp=" "
               replace="_"
               global="true" />

Unfortunately the examples given aren't terribly clear, but it's worth trying that. You should also check what happens if there aren't any underscores - you may need to use the defaultValueoption as well.

不幸的是,给出的例子不是很清楚,但值得一试。如果没有任何下划线,您还应该检查会发生什么 - 您可能还需要使用该defaultValue选项。

回答by Uwe Schindler

Here is the solution without scripting and no external jars like ant-conrib:

这是没有脚本和没有像 ant-conrib 这样的外部 jar 的解决方案:

The trick is to use ANT's resources:

诀窍是使用 ANT 的资源:

  • There is one resource type called "propertyresource" which is like a source file, but provides an stream from the string value of this resource. So you can load it and use it in any task like "copy" that accepts files
  • There is also the task "loadresource" that can load any resource to a property (e.g., a file), but this one could also load our propertyresource. This task allows for filtering the input by applying some token transformations. Finally the following will do what you want:
  • 有一种资源类型称为“propertyresource”,它类似于源文件,但提供来自该资源的字符串值的流。所以你可以加载它并在任何任务中使用它,比如接受文件的“复制”
  • 还有一个任务“loadresource”可以将任何资源加载到属性(例如,文件),但这个任务也可以加载我们的属性资源。此任务允许通过应用一些标记转换来过滤输入。最后,以下将执行您想要的操作:
<loadresource property="propB">
  <propertyresource name="propA"/>
  <filterchain>
    <tokenfilter>
      <filetokenizer/>
      <replacestring from=" " to="_"/>
    </tokenfilter>
  </filterchain>
</loadresource>

This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.

这将用“_”替换propA中的所有“”并将结果放在propB中。“filetokenizer”将整个输入流(我们的财产)视为一个标记,并在其上应用字符串替换。

You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html

您可以使用其他令牌过滤器进行其他花哨的转换:http://ant.apache.org/manual/Types/filterchain.html

回答by dnault

If ant-contrib isn't an option, here's a portable solution for Java 1.6 and later:

如果 ant-contrib 不是一个选项,这里有一个适用于 Java 1.6 及更高版本的可移植解决方案:

<property name="before" value="This is a value"/>
<script language="javascript">
    var before = project.getProperty("before");
    project.setProperty("after", before.replaceAll(" ", "_"));
</script>
<echo>after=${after}</echo>

回答by mgaert

In case you want a solution that does use Ant built-ins only, consider this:

如果您想要一个使用 Ant 内置函数的解决方案,请考虑:

<target name="replace-spaces">
    <property name="propA" value="This is a value" />
    <echo message="${propA}" file="some.tmp.file" />
    <loadfile property="propB" srcFile="some.tmp.file">
        <filterchain>
            <tokenfilter>
                <replaceregex pattern=" " replace="_" flags="g"/>
            </tokenfilter>
        </filterchain>
    </loadfile>
    <echo message="$${propB} = &quot;${propB}&quot;" />
</target>

Output is ${propB} = "This_is_a_value"

输出是 ${propB} = "This_is_a_value"

回答by Rebse

Two possibilities :

两种可能性:

via script task and builtin javascript engine (if using jdk >= 1.6)

通过脚本任务和内置 javascript 引擎(如果使用 jdk >= 1.6)

<project>

 <property name="propA" value="This is a value"/>

 <script language="javascript">
  project.setProperty('propB', project.getProperty('propA').
   replace(" ", "_"));
 </script>
 <echo>$${propB} => ${propB}</echo>

</project>

or using Ant addon Flaka

或使用Ant 插件 Flaka

<project xmlns:fl="antlib:it.haefelinger.flaka">

 <property name="propA" value="This is a value"/>

 <fl:let> propB := replace('${propA}', '_', ' ')</fl:let>

 <echo>$${propB} => ${propB}</echo>

</project>

to overwrite exisiting property propA simply replace propB with propA

要覆盖现有的属性 propA,只需将 propB 替换为 propA

回答by Jarekczek

Use some external app like sed:

使用一些外部应用程序,如 sed:

<exec executable="sed" inputstring="${wersja}" outputproperty="wersjaDot">
  <arg value="s/_/./g"/>
</exec>
<echo>${wersjaDot}</echo>

If you run Windows get it googling for "gnuwin32 sed".

如果您运行 Windows,请在谷歌上搜索“gnuwin32 sed”。

The command s/_/./greplaces every _with .This script goes well under windows. Under linux arg may need quoting.

该命令s/_/./g将 each 替换_.此脚本在 windows 下运行良好。在 linux arg 下可能需要引用。

回答by Avinash R

Here's a more generalized version of Uwe Schindler's answer:

这是Uwe Schindler 答案的更概括版本:

You can use a macrodefto create a custom task.

您可以使用 amacrodef创建自定义任务。

<macrodef name="replaceproperty" taskname="@{taskname}">
    <attribute name="src" />
    <attribute name="dest" default="" />
    <attribute name="replace" default="" />
    <attribute name="with" default="" />
    <sequential>
        <loadresource property="@{dest}">
            <propertyresource name="@{src}" />
            <filterchain>
                <tokenfilter>
                    <filetokenizer/>
                    <replacestring from="@{replace}" to="@{with}"/>
                </tokenfilter>
            </filterchain>
        </loadresource>
    </sequential>
</macrodef>

you can use this as follows:

您可以按如下方式使用它:

<replaceproperty src="property1" dest="property2" replace=" " with="_"/>

this will be pretty useful if you are doing this multiple times

如果您多次执行此操作,这将非常有用

回答by Jin Kwon

Adding an answer more complete example over a previous answer

先前的答案上添加更完整的答案示例

<property name="propB_" value="${propA}"/>
<loadresource property="propB">
  <propertyresource name="propB_" />
  <filterchain>
    <tokenfilter>
      <replaceregex pattern="\." replace="/" flags="g"/>
    </tokenfilter>
  </filterchain>
</loadresource>

回答by River Rock

Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html) can.

属性无法更改,但 antContrib 变量 ( http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html) 可以。

Here is a macro to do a find/replace on a var:

这是一个对 var 进行查找/替换的宏:

    <macrodef name="replaceVarText">
        <attribute name="varName" />
        <attribute name="from" />
        <attribute name="to" />
        <sequential>
            <local name="replacedText"/>
            <local name="textToReplace"/>
            <local name="fromProp"/>
            <local name="toProp"/>
            <property name="textToReplace" value = "${@{varName}}"/>
            <property name="fromProp" value = "@{from}"/>
            <property name="toProp" value = "@{to}"/>

            <script language="javascript">
                project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
            </script>
            <ac:var name="@{varName}" value = "${replacedText}"/>
        </sequential>
    </macrodef>

Then call the macro like:

然后像这样调用宏:

<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>

Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.

上面的代码使用javascript split then join,比regex快。“本地”属性被传递给 JavaScript,所以没有属性泄漏。

回答by user2163960

Just an FYI for answer Replacing characters in Ant property- if you are trying to use this inside of a maven execution, you can't reference maven variables directly. You will need something like this:

仅供参考替换 Ant 属性中的字符- 如果您尝试在 Maven 执行中使用它,则不能直接引用 Maven 变量。你将需要这样的东西:

...
<target>
<property name="propATemp" value="${propA}"/>
    <loadresource property="propB">
    <propertyresource name="propATemp" />
...