Search code examples
javaregexstringurlmailto

Java get email address from url


I have this url mailto:email@gmail.com?subject=... and I want to extract the email address.

I've done this:

String[] s = url.split("[:?]");

It works but I'm not happy with this solution.

Is there a way to do this using a regular expression or something better than what I have done?


Solution

  • You can try extracting only

    protocol:path?query
             ^^^^
    

    part with URL#getPath

    String email= new URL("mailto:email@gmail.com?subject").getPath();
    
    System.out.println(email);
    

    Output: email@gmail.com


    But you can also simply use positions of first : and first ? after them to determine where should you cut the string.

    String data = "mailto:email@gmail.com?subject";
    int colonIndex = data.indexOf(':')+1;
    int questionMarkIndex = data.indexOf('?',colonIndex);
    String email = null;
    if (questionMarkIndex>colonIndex){
        email = data.substring(colonIndex,questionMarkIndex);
    }else{//there was no `?` after `:`
        email = data.substring(colonIndex);
    }
    System.out.println(email);
    

    But actually I am not sure why you are "not happy" with split("[:?]"). It is perfectly fine and nice solution:

    String data = "mailto:email@gmail.com?subject";
    String email = data.split("[:?]")[1];
    
    System.out.println(email);
    

    which will also handle case where there is no ? at the end.