我在下面提到了完整路径字符串:
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 );
}
}
最佳答案
无论您的平台如何(即 \
或 /
),这对您来说都应该有点灵活
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);
关于java - 将旧路径替换为新路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43258123/