我有以下字符串,我想使用 java 正则表达式来获得以下结果。
String s = "/accounts/main/index/page.txt"
String[] result = {"/accounts/", "/accounts/main/", "/accounts/main/index/"};
也就是说,我想获得“父目录层次结构”(这不一定是目录结构)。
注意:字符串“s”是动态分配的,所以可能是不同级别的目录。
我有以下内容,但我不确定如何编译将返回我想要的内容的正则表达式。我知道我想要的只能返回一个结果,数组中的最后一项:
Pattern p = Pattern.compile("^/.+/"); //how do i set up this regex to give me required results.
String s = "/accounts/main/index/page.xhtml";
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group());
}
最佳答案
我不会为此使用正则表达式。类似
的东西呢?String[] split = s.split("/");
StringBuilder sb = new StringBuilder(s.lastIndexOf('/') + 1); // our result
sb.append('/'); // initial "/"
for (int i = 0; i < split.length - 1; i++) { // we don't care about the
if (split[i].isEmpty()) // last component
continue;
sb.append(split[i]);
sb.append('/');
System.out.println(sb); // or add to an array/list/etc.
}
/accounts/ /accounts/main/ /accounts/main/index/
关于Java Regex 捕获多个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17845723/