Prevent regex match
I have the following regex \/\/.*\/.*?
and I am applying it to strings in this format:mongodb://localhost:27017/admin?replicaSet=rs
Based on the above, the returned match is: //localhost:27017/
however I don't need characters //../
, I want the result to be like this:localhost:27017
What needs to be changed to achieve this, I am fairly new to regex creation.
Edit: I am using Java 1.7 to execute this regex statement.
source to share
You can use this approach replaceAll
in Java if you don't want to use Matcher
:
System.out.println("mongodb://localhost:27017/admin?replicaSet=rs".replaceAll("mongodb://([^/]*).*", "$1"));
Here I am assuming you have 1 occurrence of mongodb url. mongodb://
matches a sequence of characters literally, ([^/]*)
matches a sequence of 0 or more characters other than /
, and stores them in the > / a> 1 group (we'll use a backreference $1
for this group to get the text in the replacement pattern). .*
matches all characters 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 - (?<=//)[^/]*
- again matches a sequence of 0 or more characters other than /
(c [^/]*
), but make sure to come before this sequence //
. (?<=//)
is a positive lookbehind that does not consume characters and thus does not return them in a match.
source to share