-2

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?

Ale
  • 2,282
  • 5
  • 38
  • 67
  • 1
    Will your String always be of the form `mailto:email@host.domain?stuff`? Because if so, you don't need regex to parse this. Just remove the leading piece, and everything after/including the `?` – Kon Feb 05 '15 at 17:23
  • Why the 2 negatives votes? Of course I've searched for it, the problem is I don't know what I'm looking for... – Ale Feb 05 '15 at 17:35
  • I suspect you got down-voted because "*I'm not happy with this solution.*" says nothing about why you consider this solution as bad. Because of this we also don't know if our alternative solution will be good or not, which makes your question hard to answer. – Pshemo Feb 05 '15 at 17:38

2 Answers2

3

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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Thank you very much for your answer! I was just asking, I thought using this `split` method was not fine, or `regex` were better. – Ale Feb 06 '15 at 08:45
1

Use the URL class and call the getPath method.

For example:

URL url = new URL("mailto:email@gmail.com?subject=foo");
String email = url.getPath();
Claudio Corsi
  • 329
  • 1
  • 4