Search code examples
javastringcut

Java - Cut a String from the right side till specific character


I have the following String with a file path like that:

/Users/Fabian/Desktop/R5X5.mps

I do now want to just geht the filename meaning - everything from the right side till '/'.

In that case: R5X5.mps

What would be the most efficient way to do that ?

Can this be resolved with native java methods or do I need to build an regular expression ?


Solution

  • Use regex. It's pretty straightforward:

    String last = str.replaceAll(".*/", "");
    

    This regex says "everything up and including a slash", which gets replaced by nothing (effectively "deleting" it).

    I don't think anyone would use the word "building" to describe the effort required to type ".*/".