NON-REGEX SOLUTION
In Java, you can use URL class to parse URLs. So, the best solution would be:
URL aURL = new URL("http://www.website.com/page/support/28685875?JK.kj_id=");
String str = aURL.getPath().substring(aURL.getPath().lastIndexOf("/") + 1);
System.out.println(str);
See demo
See Parsing a URL tutorial.
REGEX SOLUTION
The regex that you are looking for should match the last /
followed by digits or any symbols up to ?
that might also followed by optional characters other than /
to the end of string. The part between /
and ?
can be captured into a group and then used.
\/([^\/]*)\?[^\/]*$
See regex demo
The negated character class [^\/]
matches any character but a /
. Group 1 will hold the value you need.
To only match the substring you need to use lookarounds:
(?<=/)[^/]*(?=[?][^/]*$)
^^^^^ ^^^
or a simpler one:
(?<=/)[^/?]+(?=[?]|$)
See demo
Java code:
String s = "http://w...content-available-to-author-only...e.com/page/support/28685875?JK.kj_id=";
Pattern pattern = Pattern.compile("(?<=/)[^/?]+(?=[?]|$)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group());
}
However, you can use a capturing based regex and access the Group 1 using matcher.group(1)
.
The (?<=/)([^/?]+)(?=[?]|$)
pattern does the following:
(?<=/)
- checks if there is a /
before the currently tested position in the string (if failed, the index is advanced, next position is tested)
[^/?]+
- matches 1 or more characters other than /
and ?
(no escaping necessary here)
(?=[?]|$)
- checks if the next character is ?
or end of string. If not, fail the match.