说我有一个字符串:
/first/second/third
Run Code Online (Sandbox Code Playgroud)
我希望在/的最后一个实例之后删除所有内容,因此我最终会:
/first/second
Run Code Online (Sandbox Code Playgroud)
我会用什么正则表达式?我试过了:
String path = "/first/second/third";
String pattern = "$(.*?)/";
Pattern r = Pattern.compile(pattern2);
Matcher m = r.matcher(path);
if(m.find()) path = m.replaceAll("");
Run Code Online (Sandbox Code Playgroud)
你的意思是这样的吗?
s = s.replaceAll("/[^/]*$", "");
Run Code Online (Sandbox Code Playgroud)
或者如果您使用路径更好
File f = new File(s);
File dir = f.getParent(); // works for \ as well.
Run Code Online (Sandbox Code Playgroud)