简体   繁体   中英

Removing regular expression from string

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?

try this

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

didn't test, should work.

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));

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));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM