2

In this question I asked for a regex to turn /abc/def/ghi into {/abc/def/ghi, /def/ghi, /ghi}. The answer was to use lookahead with the expression (?=(/.*)).

Is there a regex to capture from the same string {/abc, /abc/def, /abc/def/ghi}? (Order is not important.)

Community
  • 1
  • 1
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
  • I haven't been able to accomplish this with a pure regex. The trouble is you're trying to get multiple results without advancing the matcher's starting index. Since the index is really the matcher's only relevant state it would have no way of returning something different on the second invocation than on the first. So you'd probably be better off with a non-regex solution but rather searching for indices of `/` manually. – Mark Peters Oct 14 '11 at 04:06
  • I might have spoken too soon; I've posted an answer but it's not too elegant. – Mark Peters Oct 14 '11 at 04:31

2 Answers2

1

Ok, here's a solution that works for your one and only test case, though I haven't found a way to group it into one nice group:

Matcher m = Pattern.compile("((?<=(^.*))(/[^/]*))").matcher("/abc/def/ghi");
while (m.find()) {
   System.out.println(m.group(2) + m.group(3));
}

It essentially finds each /xxx substring as they appear but then also concatenates everything before that match. This works for your test case but might have limitations for more complex cases.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
-1

This will do what you want:

(?<=(/.*)\b)
porges
  • 30,133
  • 4
  • 83
  • 114