Java正则表达式:删除最后一个字符实例后的所有内容

3

假设我有一个字符串:

/first/second/third

我想删除最后一个斜杠之后的所有内容,所以我希望最终结果为:
/first/second

我该使用什么正则表达式呢?我已经尝试过以下内容:
String path = "/first/second/third";
String pattern = "$(.*?)/";
Pattern r = Pattern.compile(pattern2);
Matcher m = r.matcher(path);
if(m.find()) path = m.replaceAll("");
4个回答

10

为什么要在这里使用正则表达式?使用lastIndexOf查找最后一个/字符。如果找到了,那就使用substring提取它前面的所有内容。


1
+1,不过我认为楼主想要提取它之前的所有内容。 - DannyMo
1
@damo 你说得对,我已经更新了我的回答(和子字符串链接)。 - rgettman

5
你的意思是像这样吗?
s = s.replaceAll("/[^/]*$", "");

如果您使用路径,则更好。

File f = new File(s);
File dir = f.getParent(); // works for \ as well.

你的意思是replaceAll吧。 - arshajii
@arshajii 是的,replace() 函数不支持正则表达式。 - Peter Lawrey

1
如果您有包含字符(无论是辅助码点还是非辅助码点)的字符串,则可以使用Pattern.quote并匹配反向字符集直至结束,如下所示:
String myCharEscaped = Pattern.quote(myCharacter);
Pattern pattern = Pattern.compile("[^" + myCharEscaped + "]*\\z");

应该这样做,但实际上你可以直接使用lastIndexOf,如下:

myString.substring(0, s.lastIndexOf(myCharacter) + 1)

获取代码点作为字符串,只需执行以下操作:
new StringBuilder().appendCodePoint(myCodePoint).toString()

0

尽管答案避免了正则表达式模式和匹配器,但它对性能(编译的模式)很有用,而且仍然相当简单,值得掌握。 :)

不确定为什么您在前面加上了"$"。 请尝试以下任一选项:

  1. 匹配起始组

    String path = "/first/second/third";
    String pattern = "^(.*)/";  // * = "贪婪": 从开头到最后一个 "/" 的最大字符串
    Pattern r = Pattern.compile(pattern2);
    Matcher m = r.matcher(path);
    if (m.find()) path = m.group();
    
  2. 去除尾部匹配:

    String path = "/first/second/third";
    String pattern = "/(.*?)$)/"; // *? = "勉强": 从最后一个 "/" 到结尾的最小字符串
    Pattern r = Pattern.compile(pattern2);
    Matcher m = r.matcher(path);
    if (m.find()) path = m.replace("");
    

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