trouble using replaceregexp when replacing string DIR location

纵饮孤独 提交于 2020-02-03 10:49:28

问题


I am having trouble in doing this. there is 1 batch file with this line:

set TEST_DIR=C:\temp\dir1

I just want to set some new value to TEST_DIR

But, when I use in my ant script, it escapes forward slashes and gives this result:

set TEST_DIR=C:homedir2

Instead, I want to give it:

set TEST_DIR=C:\home\dir2

I am using this command:

<replaceregexp file="${MT_BATCH_FILE_LOCATION}\myfile.bat" match="TEST_DIR=C:\\temp\\dir1" replace="TEST_DIR=C:\home\dir2" byline="true" />

回答1:


You can get the result you want by using this replace pattern:

 replace="TEST_DIR=C:\\\\home\\\\dir2"

The reason is that you must escape the backslash once for the regex and once for Java - backslash is an escape character in both those contexts.

In answer to your subsequent questions in comments...

  1. I expect the answer will be the same. You will need to double-escape the backslash in the value of ${new_loc}, i.e. use C:\\\\my_projcode not C:\my_projcode.

  2. If new_loc is coming in as an environment variable, you could use the propertyregex task from ant-contrib to escape backslashes in the value:

    <project default="test">
    
      <!-- import ant-contrib --> 
      <taskdef resource="net/sf/antcontrib/antlib.xml">
        <classpath>
          <pathelement location="C:/lib/ant-contrib/ant-contrib-1.0b3.jar"/>
        </classpath>
      </taskdef>
    
      <target name="test">
    
        <!-- load environment variables -->
        <property environment="env"/>
    
        <!-- escape backslashes in new_loc -->
        <propertyregex property="loc" input="${env.new_loc}" regexp="\\" replace="\\\\\\\\\\\\\\\\" />
    
        <echo message="env.new_loc: ${env.new_loc}"/>
        <echo message="loc: ${loc}"/>
    
        <!-- do the replace --> 
        <replaceregexp file="test.bat" match="TEST_DIR=C:\\temp\\dir1" replace="TEST_DIR=${loc}\\\\home\\\\dir2" byline="true" />
    
      </target>
    

Output:

c:\tmp\ant>set new_loc=c:\foo\bar

c:\tmp\ant>ant
Buildfile: c:\tmp\ant\build.xml

test:
     [echo] new_loc: c:\foo\bar
     [echo] env.new_loc: c:\foo\bar
     [echo] loc: c:\\\\foo\\\\bar

BUILD SUCCESSFUL
Total time: 0 seconds

c:\tmp\ant>type test.bat
set TEST_DIR=c:\foo\bar\home\dir2



回答2:


I have found another simple solution use replace instead of replaceregexp.

<replace file="${MT_BATCH_FILE_LOCATION}\myfile.bat"
                            token='TEST_DIR=C:\temp\dir1'
                    value='TEST_DIR=${new_loc}\home\dir2' />


来源:https://stackoverflow.com/questions/8077565/trouble-using-replaceregexp-when-replacing-string-dir-location

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!