简体   繁体   English

从字符串中删除正则表达式

[英]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. 我想删除它末尾的*/ part。 In this case this is something/ . 在这种情况下,这是something/ How can I achive that with java? 我怎样才能用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中删除最后一个过去:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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