1

我正在使用 Maven 3.2.3。我的 pom.xml 文件中有这个插件……</p>

                    <!-- creates a test database script from the properties file -->
                    <plugin>
                            <groupId>com.google.code.maven-replacer-plugin</groupId>
                            <artifactId>replacer</artifactId>
                            <version>1.5.3</version>
                            <executions>
                                    <execution>
                                            <phase>compile</phase>
                                            <goals>
                                                    <goal>replace</goal>
                                            </goals>
                                    </execution>
                            </executions>
                            <configuration>
                                    <file>src/test/resources/META-INF/db-test-data.sql.templ</file>
                                    <outputFile>target/test-classes/db-test-data.sql</outputFile>
                                    <tokenValueMap>src/test/resources/test.properties</tokenValueMap>
                            </configuration>
                    </plugin>

我注意到当我的“test.properties”文件包含这样的属性时

test.sample.school2.name=Middle $ample Elementary #2

插件执行时出现以下错误...</p>

[ERROR] Failed to execute goal com.google.code.maven-replacer-plugin:replacer:1.5.3:replace (default) on project core: Illegal group reference -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.

问题在于替换值中的“$”。如果我删除它,一切都很好。但是,有时被替换的值会有一个“$”。有没有办法将插件配置为接受“$”,或者除此之外,是否有一个等效的插件我可以使用来实现与上述相同的功能?

4

1 回答 1

1

您应该转义$令牌(和其他此类正则表达式符号):

test.sample.school2.name=Middle \$ample Elementary #2

正如您所知,该$ 字符用于在正则表达式替换期间表示匹配组(因此出现错误消息)。

当然,这与加载时属性文件中的键所需的转义无关,但这个插件可能会replaceAll支持正则表达式。

引用它的javadoc

请注意,替换字符串中的反斜杠 (\) 和美元符号 ($) 可能会导致结果与将其视为文字替换字符串时的结果不同;见Matcher.replaceAll。如果 Matcher.quoteReplacement(java.lang.String)需要,用于抑制这些字符的特殊含义。

但显然,replacer插件的代码不使用quoteReplacement来转义任意替换字符串(在这种情况下,它是字符串: "Middle $ample Elementary #2"),因此您必须自己转义它。


如果您根本不打算使用正则表达式匹配/替换,您可以在插件配置中将regex标志设置为:false

<configuration>
  <file>src/test/resources/META-INF/db-test-data.sql.templ</file>
  <outputFile>target/test-classes/db-test-data.sql</outputFile>
  <tokenValueMap>src/test/resources/test.properties</tokenValueMap>
  <regex>false</regex>
</configuration>
于 2015-08-08T21:12:17.570 回答