2

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

0

1 Answer 1

7

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

RegEx Details:

  • ^: Start
  • mydb://: Match mydb://
  • ([^:]+): Match 1+ of any character other than : and capture in group #1
  • :: Match a :
  • ([^@]+): Match 1+ of any character other than @ and capture in group #2
  • @: Match a @
  • [^:]+: Match 1+ of any character other than :
  • :: Match a :
  • \\d+: Match 1+ digits
  • $: End

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")
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! Can I do this using one call to String replace method (see my EDIT above)?
You'll need to call String#replaceAll twice for user and password separately.
I believe when using replace the regexp has to be changed a bit as we need to replace what we don't want with "" instead of extracting the user and the passwpord?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.