Sometimes regex
can be a little overwhelming, especially if you're not familiar with it. It even can make code more difficult to read (Disadvantages of using Regular Expressions). Now, don't get me wrong, I like to use regex
when the task is simple enough for it. IMO, you're better off solving this without regex
. You can design a method to find the index location of the 5th "/" and then just return the substring.
Something like:
public static void main(String[] args) {
String url = "http://daniel.mirimar.net.nz/Sites/reginald/DDD/CD";
System.out.println(substringNthOccurrence(url, '/', 5));
}
public static String substringNthOccurrence(String string, char c, int n) {
if (n <= 0) {
return "";
}
int index = 0;
while (n-- > 0 && index != -1) {
index = string.indexOf(c, index + 1);
}
return index > -1 ? string.substring(0, index + 1) : "";
}
Results:
http://daniel.mirimar.net.nz/Sites/reginald/