Reputation: 3276
I have a String in this format:
mydb://<user>:<password>@<host>:27017
And I would like to use Java regexp in order to extract the <user>
and <password>
strings from the String. What would be the best way doing so?
EDIT:
I would like to be able to use this regexp in the String's replace method so that I'm left only with the relevant user and password Strings
Upvotes: 0
Views: 2401
Reputation: 785058
You can use this regex (Pattern)
Pattern p = Pattern.compile("^mydb://([^:]+):([^@]+)@[^:]+:\\d+$");
And then capture group #1 and #2 will have your user and password respectively.
Code:
String str = "mydb://foo:bar@localhost:27017";
Pattern p = Pattern.compile("^mydb://([^:]+):([^@]+)@[^:]+:\\d+$");
Matcher matcher = p.matcher(str);
if (matcher.find())
System.out.println("User: " + matcher.group(1) + ", Password: "
+ matcher.group(2));
OUTPUT:
User: foo, Password: bar
EDIT: Based on your comments: if you want to use String methods then:
String regex = "^mydb://([^:]+):([^@]+)@[^:]+:\\d+$";
String user = str.replaceAll(regex, "$1");
String pass = str.replaceAll(regex, "$2")
Upvotes: 5