使用Java中的string.replaceFirst/string.replaceLast正则表达式删除末尾第二个斜杠后面的所有内容。

3
我有这样的路径 /my/long/path/which/will/never/ends/。我想要删除离结尾第二个斜杠后面的所有内容(所以输出结果将会是 /my/long/path/which/will/never/)。我该怎么做?我只能使用Java中的String.replaceFirst或String.replaceAll方法。
谢谢。
1个回答

4

您可以使用:

String str = "/my/long/path/which/will/never/ends/";
str = str.replaceFirst("[^/]+/$", "");
//=> /my/long/path/which/will/never/

RegEx Demo


2
[^/]+ 匹配一个或多个非斜杠字符,后跟 /,然后输入结束,从而从输入的末尾删除 ends/any-thing-here/ - anubhava

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接