2017-04-06 128 views
0

我已经下文提到的完整路径字符串:替换旧路径新路径

String originalpath = C:\test\sample\batchmatch\internal\a\b\a.pdf 

我需要更换新的路径

路径,例如第一部分:

oldpath = C:\test\sample\batchmatch\internal\to 
new path = C:\testdemo\sampledemo\batchmatchdemo\internal 

我已经尝试了下面提到的方法,但它不起作用。

String newpath = originalpath.replaceAll(oldpath,newpath); 

你能帮我吗?

class Demo { 
    public static void main(String[] args) { 
     String originalpath = C:\test\sample\batchmatch\internal\a\b\a.pdf; 
     String oldpath = C:\test\sample\batchmatch\internal\; 
     String newpath = C:\testdemo\sampledemo\batchmatchdemo\internal; 
     String relacepath = a.replaceAll(oldpath ,newpath); 
     System.out.println("replacepath::"+ relacepath); 
    } 
} 
+2

你看过了'replaceAll'的文档?你的要求不是很清楚。 – tnw

+0

显示您正在使用的实际可运行代码会重现该问题,而不是一些无法运行的近似值。请参阅:如何创建[mcve]。 –

+0

@tnw需求是我需要将C:\ test \ sample \ batchmatch \ internal \替换为C:\ testdemo \ sampledemo \ batchmatchdemo \ internal – user7615212

回答

0
public static void main(String[] args) { 
    String originalpath = "C:/test/sample/batchmatch/internal/a/b/a.pdf"; 
    String oldpath = "C:/test/sample/batchmatch/internal"; 
    String path = "C:/testdemo/sampledemo/batchmatchdemo/internal"; 
    System.out.println(originalpath); 
    String newpath = originalpath.replaceAll(oldpath,path); 

    System.out.println(newpath); 

    } 
1

这应该是一个有点灵活,你不管你的平台(即\/

String oldPath = "C:\\test\\sample\\batchmatch\\internal\\a\\b\\a.pdf".replaceAll("(\\\\+|/+)", "/"); 
    String newPath = "C:\\testdemo\\sampledemo\\batchmatchdemo\\internal".replaceAll("(\\\\+|/+)", "/"); 

    String partToKeep = "\\a\\b\\a.pdf".replaceAll("(\\\\+|/+)", "/"); 
    String partToReplace = oldPath.substring(0, oldPath.indexOf(partToKeep)); 

    String replacedPath = oldPath.replaceAll(partToReplace, newPath).replaceAll("(\\\\+|/+)", Matcher.quoteReplacement(System.getProperty("file.separator"))); 
    System.out.println(replacedPath); 
0

有几种方法来做到这一点,例如:

String communPath = "C:/test/sample/batchmatch/internal"; 
    String secondpartOfPath = "https://stackoverflow.com/a/b/a.pdf"; 
    String originalpath = communPath.concat(secondpartOfPath); 
    String newPath = "C:/testdemo/sampledemo/batchmatchdemo/internal"; 
    System.out.println(originalpath); 
    String path = originalpath.replaceAll(communPath, newPath); 
    System.out.println(path); 

originalpath:C:/test/sample/batchmatch/internal/a/b/a.pdf

路径:C:/testdemo/sampledemo/batchmatchdemo/internal/a/b/a.pdf