【问题标题】:Ant is not replacing multiple instances in the same lineAnt 没有替换同一行中的多个实例
【发布时间】:2016-06-13 14:19:19
【问题描述】:

我正在使用 replaceregexp 替换文件中的特定匹配项。每当一行中有多个匹配项时,它只会替换该行的最后一个实例。

Eg:
Input:
    f1.lblTest.text != null && f1.lblTest.text != ""
Reg EX:
 <replaceregexp file="mod1.js" match="(.*)f1(\.|\[&quot;)lblTest(\.|&quot;\]|\[&quot;)(.*)" replace="\1f1\2lblTestNew\3\4 \\/\\/Modified" flags="g">
Expected Output:
    f1.lblTestNew.text != null && f1.lblTestNew.text != "" //Modified
Actual Output:
    f1.lblTest.text != null && f1.lblTestNew.text != "" //Modified
With this <replaceregexp file="mod1.js" match="f1(\.|\[&quot;)$lblTest(\.|&quot;\]|\[&quot;)" replace="f1\1lblTestNew\2 \\/\\/Modified" flags="g"> I'm getting the below output
f1.lblTestNew. //Modifiedtext != null && f1.lblTestNew. //Modifiedtext != "".
 With this <replaceregexp file="mod1.js" match="f1(\.|\[&quot;)$lblTest(\.|&quot;\]|\[&quot;)" replace="f1\1lblTestNew\2" flags="g"> I'm getting the below output
f1.lblTestNew.text != null && f1.lblTestNew.text != "" This is ok but I really wanted a comment that lets the users know that this is modified and if they want they can modify again.

请提出任何解决方案。

注意:我已经尝试了带和不带“署名”的 g,m,s 标志,但它们不起作用。

【问题讨论】:

  • 发生这种情况是因为双方都有(.*)。删除它们和替换模式中的反向引用。试试&lt;replaceregexp file="mod1.js" match="f1(\.|\[&amp;quot;)$lblTest(\.|&amp;quot;\]|\[&amp;quot;)" replace="f1\1lblTestNew\2 \\/\\/Modified" flags="g"&gt;
  • 您好 Wiktor,感谢您的建议,通过您的更改,我得到了此输出 f1.lblTestNew. //Modifiedtext != null &amp;&amp; f1.lblTestNew. //Modifiedtext != "". 。我明白为什么(.*) 会导致问题。我只希望在行尾的 //Modified 一次。如果我删除了`\\/\\/Modified`,它会被正确替换并且输出是f1.lblTeststudio1.text != null &amp;&amp; f1.lblTeststudio1.text != "",但我想要//Modified,这样我们就知道它是由Ant脚本修改的,这对用户,以便用户可以根据需要再次手动修改。有什么建议吗?
  • 我现在明白了,你想替换多个occ。的一些文本在末尾添加文本。看起来很棘手,你不觉得吗?你不能使用我的建议与f1\1lblTestNew\2 作为替换字符串,然后将//Modified 注释附加到另一个规则,比如(.*f1(\.|\[&amp;quot;)lblTestNew(\.|&amp;quot;\]|\[&amp;quot;).*) 并替换为\1 // Modified
  • 嗨,Wiktor 再次感谢您的回复,我昨天已经尝试过(首先添加评论然后替换),但问题是每个文件和每个文件都有两个操作(正则表达式)匹配,这对于具有大量行数和大量文件的文件将非常耗时。所以我正在寻找一个可以同时服务于两者的单一操作。
  • 不可能,这是不可能的,您不能使用带有条件替换模式的 Java 或 JavaScript 正则表达式。只有 Boost 和 PCRE2 允许这样做。 如果文本 (//Modified) 存在于字符串中,那么,我认为我们可以提供帮助,但在原始字符串中缺少它的情况下就不行了。

标签: java regex replace ant


【解决方案1】:

由于您有no conditional replacement pattern support in Ant replaceregexp,因此只有一种可能的解决方案,涉及 2 个步骤:

  • &lt;replaceregexp file="mod1.js" match="f1(\.|\[&amp;quot;)$lblTest(\.|&amp;quot;\]|\[&amp;quot;)" replace="f1\1lblTestNew\2" flags="g"&gt; 将所有 lblTest 替换为 lblTestNew 文本
  • //Modified 子字符串附加到字符串的末尾,例如&lt;replaceregexp file="mod1.js" match="(.*f1(\.|\[&amp;quot;)lblTestNew(\.|&amp;quot;\]|\[&amp;quot;).*)" replace="\1 // Modified"&gt;

【讨论】:

  • 感谢 Wiktor,最后我不得不遵循这两个步骤。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 2010-09-18
  • 2022-12-10
  • 2015-10-04
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多