4

I have the following string which i want to use java regex to get the following results.

String s  = "/accounts/main/index/page.txt"
String[] result = {"/accounts/", "/accounts/main/", "/accounts/main/index/"};

That is, i would like to get the 'parent directory hierarchy' (This does not have to be a a directory structure).

NOTE: The string "s" is dynamically assigned, so it may be different levels of directory.

I have the following, but i am unsure of how to compile a regex that will return what i want. i know what i want can only return one result, the last entry in the array:

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

5 回答 5

3

我不会为此使用正则表达式。类似的东西怎么样

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.
}
/帐户/
/帐户/主要/
/帐户/主/索引/
于 2013-07-24T22:25:26.230 回答
2

你问的是不可能的;这种方式find有效,每场比赛只能在上一场比赛结束后匹配。但是,您可以编写:

final Pattern p = Pattern.compile("[^/]/");
final String s = "/accounts/main/index/page.xhtml";
final Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println(s.substring(0, m.end()));
}

或者,要获取一个数组:

final Pattern p = Pattern.compile("[^/]/");
final String s = "/accounts/main/index/page.xhtml";
final Matcher m = p.matcher(s);
final List<String> resultList = new ArrayList<String>();
while (m.find()) {
    resultList.add(s.substring(0, m.end()));
}
final String[] resultArr = resultList.toArray(new String[resultList.size()]);

(免责声明:未经测试。)

于 2013-07-24T22:25:32.500 回答
1

另一种方式:

Pattern p = Pattern.compile("/[^/]+"); 
String s = "/accounts/main/index/page.xhtml";
String dir = "";
Matcher m = p.matcher(args[0]);
while(m.find()){
  dir += m.group();
  System.out.println(dir + "/");
}
于 2013-07-24T22:30:43.830 回答
0

正则表达式最初可以拆分,但您必须添加一些代码:

String parts = a.split("(?<!^)(?=/)");
for (int i = 0; i < parts.length - 2; i++)
    parts[i + 1] = parts[i] + parts[i + 1];
于 2013-07-24T22:38:13.433 回答
0

实际上可以使用正则表达式来做到这一点,这将适用于您的示例:

Pattern p = Pattern.compile("^(((/[^/]+/)[^/]+/)[^/]+/)");
String s = "/accounts/main/index/page.xhtml";
Matcher m = p.matcher(s);
while (m.find())
{
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(3));
}

然而,你不能有一个匹配每个案例的正则表达式。但是由于正则表达式的结构定义明确,您当然可以根据目录结构的深度动态构建它,然后每次编译它。

于 2013-07-24T22:34:25.260 回答