1

I have the following string:

/home/user/Documents/something/

I'd like to remove the */ part at the end of it. In this case this is something/. How can I achive that with java?

1
  • Try this I have tested in regularexpressplanet.com /+[a-z]+/$ Commented Mar 15, 2013 at 12:00

3 Answers 3

2

You don't need regex to do this, below is a non-regex solution using String manipulation methods:

    String s = "/home/user/Documents/something/";
    String sub =s.substring(0, s.lastIndexOf("/"));
    System.out.println(sub.substring(0,sub.lastIndexOf("/")+1));
Sign up to request clarification or add additional context in comments.

2 Comments

It's almost fine, but it removes "\something\" instead of "something\" like it should.
@soulreaver now it would :)
2

try this

str =    str.replaceAll("[^/]*/$","");

didn't test, should work.

Comments

0

You can use the following code. It will remove the last past from your String :

        String str = "/home/user/Documents/something/";

    Pattern pattern1 = Pattern.compile("(/.+?/)(\\w+?/$)");
    Matcher matcher1 = pattern1.matcher(str);

    while (matcher1.find()) {
        System.out.println(matcher1.group(1));
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.