You can use this replaceAll
approach in Java if you do not want to use Matcher
:
System.out.println("mongodb://localhost:27017/admin?replicaSet=rs".replaceAll("mongodb://([^/]*).*", "$1"));
Here, I assume you have 1 occurrence of a mongodb URL. mongodb://
matches the sequence of characters literally, the ([^/]*)
matches a sequence of 0 or more characters other than /
and stores them in a capturing group 1 (we'll use the backreference $1
to this group to retrieve the text in the replacement pattern). .*
matches all symbols up to the end of a one-line string.
See IDEONE demo
Or, with Matcher
,
Pattern ptrn = Pattern.compile("(?<=//)[^/]*");
Matcher matcher = ptrn.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
The regex here - (?<=//)[^/]*
- matches again a sequence of 0 or more characters other than /
(with [^/]*
), but makes sure there is //
right before this sequence. (?<=//)
is a positive lookbehind that does not consume characters, and thus does not return them in the match.