Remove the file prefix in the absolute path, but the prefix is ​​also part of the directory

I was wondering if there is any nice solution for the following problem:

Assuming I have a line with an absolute Path to the file, and the file has the prefix "temp_". I can crop the prefix using string.replaceFirst ().

But if I'm out of luck, "temp_" is also part of the directory on this line. How to make sure that only the last appearance will be cropped?

I can only think to take it apart myself, but was it interesting if there is magic to make it better?

To be more precise as an example:

C:\Dump\sol1\temp_results\temp_2012-04-core.pcap

It should become:

C:\Dump\sol1\temp_results\2012-04-core.pcap
+3
source share
3 answers

, id defo @goldilocks. - String, , , :

    String target = "temp_";

    String fullPath = "C:/Dump/sol1/temp_results/temp_2012-04-core.pcap";

    StringBuffer sb = new StringBuffer(fullPath);
    int end = fullPath.lastIndexOf(target) + target.length();

    System.out.println(sb.replace(fullPath.lastIndexOf(target), end, ""));
+3

Path.getFileName(), (.. ). Path (. getName(), subpath() ..) .

+4

This is another example. How to do it.

divide the common string into three parts.

1.substring till temp_ last occurence

2.last occuerence of temp_

3.substring after last occuerence of temp_

cancat 1 + 3 anyway recommend @goldilocks solution

0
source

All Articles